<commit_before>use crate::{api::prelude::*, prelude::*, proc_macros::*};

// --- KEYS --
pub static STYLE_SLIDER: &str = "slider";
static ID_THUMB: &str = "id_thumb";
static ID_TRACK: &str = "id_track";
static ID_ACCENT_TRACK: &str = "id_accent_track";
// --- KEYS --

#[derive(Copy, Clone)]
enum SliderAction {
    Move { mouse_x: f64 },
}

/// The `SliderState` is used to manipulate the position of the thumb of the slider widget.
#[derive(Default, AsAny)]
pub struct SliderState {
    action: Option<SliderAction>,
    val: f64,
    min: f64,
    max: f64,
    thumb: Entity,
    track: Entity,
    accent_track: Entity,
}

impl SliderState {
    // register an action
    fn action(&mut self, action: SliderAction) {
        self.action = Some(action);
    }

    // adjust min, max and val
    fn adjust(&mut self, ctx: &mut Context) -> bool {
        let mut has_changes = false;
        let error = f64::EPSILON;

        if (*ctx.widget().get::<f64>("min") - self.min).abs() > error {
            let min = adjust_min(
                *ctx.widget().get::<f64>("min"),
                *ctx.widget().get::<f64>("max"),
            );
            ctx.widget().set("min", min);
            self.min = min;
            has_changes = true;
        }

        if (*ctx.widget().get::<f64>("max") - self.max).abs() > error {
            let max = adjust_max(
                *ctx.widget().get::<f64>("min"),
                *ctx.widget().get::<f64>("max"),
            );
            ctx.widget().set("max", max);
            self.max = max;
            has_changes = true;
        }

        if (*ctx.widget().get::<f64>("val") - self.val).abs() > error {
            let val = adjust_val(
                *ctx.widget().get::<f64>("val"),
                *ctx.widget().get::<f64>("min"),
                *ctx.widget().get::<f64>("max"),
            );
            ctx.widget().set("val", val);
            self.val = val;
            has_changes = true;
        }

        has_changes
    }

    // adjust the thump position
    fn adjust_thumb_x(&self, ctx: &mut Context) {
        let val = *ctx.widget().get::<f64>("val");
        let min = *ctx.widget().get::<f64>("min");
        let max = *ctx.widget().get::<f64>("max");

        let thumb_width = ctx
            .get_widget(self.thumb)
            .get::<Rectangle>("bounds")
            .width();

        let track_width = ctx
            .get_widget(self.track)
            .get::<Rectangle>("bounds")
            .width();

        let thumb_x = calculate_thumb_x_from_val(val, min, max, track_width, thumb_width);

        ctx.get_widget(self.accent_track)
            .get_mut::<Constraint>("constraint")
            .set_width(thumb_x + 2.);

        ctx.get_widget(self.thumb)
            .get_mut::<Thickness>("margin")
            .set_left(thumb_x);
    }
}

impl State for SliderState {
    fn init(&mut self, _: &mut Registry, ctx: &mut Context) {
        self.thumb = ctx.child(ID_THUMB).entity();
        self.track = ctx.child(ID_TRACK).entity();
        self.accent_track = ctx.child(ID_ACCENT_TRACK).entity();

        // todo call update
    }

    fn update_post_layout(&mut self, _: &mut Registry, ctx: &mut Context) {
        if let Some(action) = self.action {
            match action {
                SliderAction::Move { mouse_x } => {
                    if *ctx.get_widget(self.thumb).get::<bool>("pressed") {
                        let thumb_width = ctx
                            .get_widget(self.thumb)
                            .get::<Rectangle>("bounds")
                            .width();
                        let track_width = ctx
                            .get_widget(self.track)
                            .get::<Rectangle>("bounds")
                            .width();
                        let slider_x = ctx.widget().get::<Point>("position").x();

                        let thumb_x =
                            calculate_thumb_x(mouse_x, thumb_width, slider_x, track_width);

                        ctx.get_widget(self.accent_track)
                            .get_mut::<Constraint>("constraint")
                            .set_width(thumb_x + 2.);

                        ctx.get_widget(self.thumb)
                            .get_mut::<Thickness>("margin")
                            .set_left(thumb_x);

                        let min = *ctx.widget().get("min");
                        let max = *ctx.widget().get("max");

                        ctx.widget().set(
                            "val",
                            calculate_val(thumb_x, min, max, thumb_width, track_width),
                        );
                    } else {
                        ctx.widget().clear_dirty();
                    }
                }
            }

            self.action = None;
            return;
        }

        if self.adjust(ctx) {
            self.adjust_thumb_x(ctx);
        }
    }
}

widget!(
    /// The `Slider` allows to use a val in a range of values.
    ///
    /// **style:** `slider`
    ///
    /// # Example
    ///
    /// ```rust
    /// Slider::new().min(0).max(100).val(50).build(ctx)
    /// ```
    Slider<SliderState>: MouseHandler {
        /// Sets or shares the min val of the range.
        min: f64,

        /// Sets or shares the max val of the range.
        max: f64,

        /// Sets or shares the current val of the range.
        val: f64,

        /// Sets or shares the background property.
        background: Brush,

        /// Sets or shares the border radius property.
        border_radius: f64,

        /// Sets or shares the border thickness property.
        border_width: Thickness,

        /// Sets or shares the border brush property.
        border_brush: Brush,

        /// Indicates if the widget is hovered by the mouse cursor.
        hover: bool,

        /// Defines the margin around the inner border.
        container_margin: Thickness,

         /// Defines the margin around the accent border.
        accent_margin: Thickness,

        /// Defines the accent_brush
        accent_brush: Brush
    }
);

impl Template for Slider {
    fn template(self, id: Entity, ctx: &mut BuildContext) -> Self {
        self.name("Slider")
            .style(STYLE_SLIDER)
            .min(0.0)
            .max(100.0)
            .val(0.0)
            .height(24.0)
            .border_radius(2.0)
            .container_margin((0, 11, 0, 11))
            .accent_margin((0, 11, 0, 11))
            .child(
                Grid::new()
                    .id(ID_TRACK)
                    .child(
                        Grid::new()
                            .margin((8, 0))
                            .child(
                                // background border
                                Container::new()
                                    .margin(("container_margin", id))
                                    .opacity(id)
                                    .border_radius(id)
                                    .background(id)
                                    .border_brush(id)
                                    .border_width(id)
                                    .build(ctx),
                            )
                            .child(
                                // accent border
                                Container::new()
                                    .id(ID_ACCENT_TRACK)
                                    .margin(("accent_margin", id))
                                    .h_align("start")
                                    .width(0)
                                    .opacity(id)
                                    .border_radius(id)
                                    .background(("accent_brush", id))
                                    .build(ctx),
                            )
                            .build(ctx),
                    )
                    .child(
                        Button::new()
                            .style("thumb")
                            .opacity(id)
                            .id(ID_THUMB)
                            .v_align("center")
                            .h_align("start")
                            .max_width(24.0)
                            .max_height(24.0)
                            .border_radius(12.0)
                            .build(ctx),
                    )
                    .build(ctx),
            )
            .on_mouse_move(move |states, p| {
                states
                    .get_mut::<SliderState>(id)
                    .action(SliderAction::Move { mouse_x: p.x() });
                false
            })
    }
}

// --- Helpers --

fn adjust_val(val: f64, min: f64, max: f64) -> f64 {
    if val < min {
        return min;
    }

    if val > max {
        return max;
    }

    val
}

fn adjust_min(min: f64, max: f64) -> f64 {
    if min > max {
        return max;
    }

    min
}

fn adjust_max(min: f64, max: f64) -> f64 {
    if max < min {
        return min;
    }

    max
}

fn calculate_thumb_x(mouse_x: f64, thumb_width: f64, slider_x: f64, track_width: f64) -> f64 {
    (mouse_x - slider_x - thumb_width)
        .max(0.0)
        .min(track_width - thumb_width)
}

fn calculate_val(thumb_x: f64, min: f64, max: f64, thumb_width: f64, track_width: f64) -> f64 {
    thumb_x / (track_width - thumb_width) * (max - min)
}

fn calculate_thumb_x_from_val(
    val: f64,
    min: f64,
    max: f64,
    track_width: f64,
    thumb_width: f64,
) -> f64 {
    (val / (max - min)) * (track_width - thumb_width)
}

// --- Helpers --

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

    const ERROR: f64 = f64::EPSILON;

    #[test]
    fn test_calculate_thumb_x() {
        assert!((0.0 - calculate_thumb_x(-1000.0, 32.0, 0.0, 100.0)).abs() < ERROR);
        assert!((0.0 - calculate_thumb_x(0.0, 32.0, 0.0, 100.0)).abs() < ERROR);
        assert!((18.0 - calculate_thumb_x(50.0, 32.0, 0.0, 100.0)).abs() < ERROR);
        assert!((36.0 - calculate_thumb_x(68.0, 32.0, 0.0, 100.0)).abs() < ERROR);
        assert!((68.0 - calculate_thumb_x(100.0, 32.0, 0.0, 100.0)).abs() < ERROR);
        assert!((68.0 - calculate_thumb_x(1000.0, 32.0, 0.0, 100.0)).abs() < ERROR);
    }

    #[test]
    fn test_calculate_val() {
        assert!((0.0 - calculate_val(0.0, 0.0, 100.0, 32.0, 100.0)).abs() < ERROR);
        assert!((50.0 - calculate_val(34.0, 0.0, 100.0, 32.0, 100.0)).abs() < ERROR);
        assert!((100.0 - calculate_val(68.0, 0.0, 100.0, 32.0, 100.0)).abs() < ERROR);
        assert!((0.0 - calculate_val(0.0, -50.0, 50.0, 32.0, 100.0)).abs() < ERROR);
        assert!((50.0 - calculate_val(34.0, -50.0, 50.0, 32.0, 100.0)).abs() < ERROR);
        assert!((100.0 - calculate_val(68.0, -50.0, 50.0, 32.0, 100.0)).abs() < ERROR);
    }

    #[test]
    fn test_adjust_val() {
        assert!((0.0 - adjust_val(-10.0, 0.0, 100.0)).abs() < ERROR);
        assert!((10.0 - adjust_val(10.0, 0.0, 100.0)).abs() < ERROR);
        assert!((100.0 - adjust_val(500.0, 0.0, 100.0)).abs() < ERROR);
    }

    #[test]
    fn test_adjust_min() {
        assert!((0.0 - adjust_min(0.0, 100.0)).abs() < ERROR);
        assert!((5.0 - adjust_min(5.0, 100.0)).abs() < ERROR);
        assert!((100.0 - adjust_min(500.0, 100.0)).abs() < ERROR);
    }

    #[test]
    fn test_adjust_max() {
        assert!((100.0 - adjust_max(0.0, 100.0)).abs() < ERROR);
        assert!((100.0 - adjust_max(100.0, 5.0)).abs() < ERROR);
        assert!((100.0 - adjust_max(0.0, 100.0)).abs() < ERROR);
    }

    #[test]
    fn test_calculate_thumb_x_from_val() {
        assert!((0.0 - calculate_thumb_x_from_val(0.0, 0.0, 100.0, 100.0, 32.0)).abs() < ERROR);
        assert!((34.0 - calculate_thumb_x_from_val(50.0, 0.0, 100.0, 100.0, 32.0)).abs() < ERROR);
        assert!((68.0 - calculate_thumb_x_from_val(100.0, 0.0, 100.0, 100.0, 32.0)).abs() < ERROR);
    }
}
<commit_msg>🐛 Fix slider not moving on resize<commit_after>use crate::{api::prelude::*, prelude::*, proc_macros::*};

// --- KEYS --
pub static STYLE_SLIDER: &str = "slider";
static ID_THUMB: &str = "id_thumb";
static ID_TRACK: &str = "id_track";
static ID_ACCENT_TRACK: &str = "id_accent_track";
// --- KEYS --

#[derive(Copy, Clone)]
enum SliderAction {
    Move { mouse_x: f64 },
}

/// The `SliderState` is used to manipulate the position of the thumb of the slider widget.
#[derive(Default, AsAny)]
pub struct SliderState {
    action: Option<SliderAction>,
    val: f64,
    min: f64,
    max: f64,
    width: f64,
    thumb: Entity,
    track: Entity,
    accent_track: Entity,
}

impl SliderState {
    // register an action
    fn action(&mut self, action: SliderAction) {
        self.action = Some(action);
    }

    // adjust min, max and val
    fn adjust(&mut self, ctx: &mut Context) -> bool {
        let mut has_changes = false;
        let error = f64::EPSILON;

        if (*ctx.widget().get::<f64>("min") - self.min).abs() > error {
            let min = adjust_min(
                *ctx.widget().get::<f64>("min"),
                *ctx.widget().get::<f64>("max"),
            );
            ctx.widget().set("min", min);
            self.min = min;
            has_changes = true;
        }

        if (*ctx.widget().get::<f64>("max") - self.max).abs() > error {
            let max = adjust_max(
                *ctx.widget().get::<f64>("min"),
                *ctx.widget().get::<f64>("max"),
            );
            ctx.widget().set("max", max);
            self.max = max;
            has_changes = true;
        }

        if (*ctx.widget().get::<f64>("val") - self.val).abs() > error {
            let val = adjust_val(
                *ctx.widget().get::<f64>("val"),
                *ctx.widget().get::<f64>("min"),
                *ctx.widget().get::<f64>("max"),
            );
            ctx.widget().set("val", val);
            self.val = val;
            has_changes = true;
        }

        // We need to check if the width has changed and update the thumb
        // accordingly, otherwise we end up with the thumb stuck in one location
        // and other similar weird behavior. See:
        // https://github.com/redox-os/orbtk/issues/468
        if get_widget_width(ctx, self.track) != self.width {
            self.width = get_widget_width(ctx, self.track);
            has_changes = true;
        }

        has_changes
    }

    // adjust the thump position
    fn adjust_thumb_x(&self, ctx: &mut Context) {
        let val = *ctx.widget().get::<f64>("val");
        let min = *ctx.widget().get::<f64>("min");
        let max = *ctx.widget().get::<f64>("max");

        let thumb_width = ctx
            .get_widget(self.thumb)
            .get::<Rectangle>("bounds")
            .width();

        let track_width = ctx
            .get_widget(self.track)
            .get::<Rectangle>("bounds")
            .width();

        let thumb_x = calculate_thumb_x_from_val(val, min, max, track_width, thumb_width);

        ctx.get_widget(self.accent_track)
            .get_mut::<Constraint>("constraint")
            .set_width(thumb_x + 2.);

        ctx.get_widget(self.thumb)
            .get_mut::<Thickness>("margin")
            .set_left(thumb_x);
    }
}

impl State for SliderState {
    fn init(&mut self, _: &mut Registry, ctx: &mut Context) {
        self.thumb = ctx.child(ID_THUMB).entity();
        self.track = ctx.child(ID_TRACK).entity();
        self.accent_track = ctx.child(ID_ACCENT_TRACK).entity();

        // todo call update
    }

    fn update_post_layout(&mut self, _: &mut Registry, ctx: &mut Context) {
        if let Some(action) = self.action {
            match action {
                SliderAction::Move { mouse_x } => {
                    if *ctx.get_widget(self.thumb).get::<bool>("pressed") {
                        let thumb_width = get_widget_width(ctx, self.thumb);
                        let track_width = get_widget_width(ctx, self.track);
                        let slider_x = ctx.widget().get::<Point>("position").x();

                        let thumb_x =
                            calculate_thumb_x(mouse_x, thumb_width, slider_x, track_width);

                        ctx.get_widget(self.accent_track)
                            .get_mut::<Constraint>("constraint")
                            .set_width(thumb_x + 2.);

                        ctx.get_widget(self.thumb)
                            .get_mut::<Thickness>("margin")
                            .set_left(thumb_x);

                        let min = *ctx.widget().get("min");
                        let max = *ctx.widget().get("max");

                        ctx.widget().set(
                            "val",
                            calculate_val(thumb_x, min, max, thumb_width, track_width),
                        );
                    } else {
                        ctx.widget().clear_dirty();
                    }
                }
            }

            self.action = None;
            return;
        }

        if self.adjust(ctx) {
            self.adjust_thumb_x(ctx);
        }
    }
}

widget!(
    /// The `Slider` allows to use a val in a range of values.
    ///
    /// **style:** `slider`
    ///
    /// # Example
    ///
    /// ```rust
    /// Slider::new().min(0).max(100).val(50).build(ctx)
    /// ```
    Slider<SliderState>: MouseHandler {
        /// Sets or shares the min val of the range.
        min: f64,

        /// Sets or shares the max val of the range.
        max: f64,

        /// Sets or shares the current val of the range.
        val: f64,

        /// Sets or shares the background property.
        background: Brush,

        /// Sets or shares the border radius property.
        border_radius: f64,

        /// Sets or shares the border thickness property.
        border_width: Thickness,

        /// Sets or shares the border brush property.
        border_brush: Brush,

        /// Indicates if the widget is hovered by the mouse cursor.
        hover: bool,

        /// Defines the margin around the inner border.
        container_margin: Thickness,

         /// Defines the margin around the accent border.
        accent_margin: Thickness,

        /// Defines the accent_brush
        accent_brush: Brush
    }
);

impl Template for Slider {
    fn template(self, id: Entity, ctx: &mut BuildContext) -> Self {
        self.name("Slider")
            .style(STYLE_SLIDER)
            .min(0.0)
            .max(100.0)
            .val(0.0)
            .height(24.0)
            .border_radius(2.0)
            .container_margin((0, 11, 0, 11))
            .accent_margin((0, 11, 0, 11))
            .child(
                Grid::new()
                    .id(ID_TRACK)
                    .child(
                        Grid::new()
                            .margin((8, 0))
                            .child(
                                // background border
                                Container::new()
                                    .margin(("container_margin", id))
                                    .opacity(id)
                                    .border_radius(id)
                                    .background(id)
                                    .border_brush(id)
                                    .border_width(id)
                                    .build(ctx),
                            )
                            .child(
                                // accent border
                                Container::new()
                                    .id(ID_ACCENT_TRACK)
                                    .margin(("accent_margin", id))
                                    .h_align("start")
                                    .width(0)
                                    .opacity(id)
                                    .border_radius(id)
                                    .background(("accent_brush", id))
                                    .build(ctx),
                            )
                            .build(ctx),
                    )
                    .child(
                        Button::new()
                            .style("thumb")
                            .opacity(id)
                            .id(ID_THUMB)
                            .v_align("center")
                            .h_align("start")
                            .max_width(24.0)
                            .max_height(24.0)
                            .border_radius(12.0)
                            .build(ctx),
                    )
                    .build(ctx),
            )
            .on_mouse_move(move |states, p| {
                states
                    .get_mut::<SliderState>(id)
                    .action(SliderAction::Move { mouse_x: p.x() });
                false
            })
    }
}

// --- Helpers --

fn get_widget_width(ctx: &mut Context, widget: Entity) -> f64 {
    ctx.get_widget(widget).get::<Rectangle>("bounds").width()
}

fn adjust_val(val: f64, min: f64, max: f64) -> f64 {
    if val < min {
        return min;
    }

    if val > max {
        return max;
    }

    val
}

fn adjust_min(min: f64, max: f64) -> f64 {
    if min > max {
        return max;
    }

    min
}

fn adjust_max(min: f64, max: f64) -> f64 {
    if max < min {
        return min;
    }

    max
}

fn calculate_thumb_x(mouse_x: f64, thumb_width: f64, slider_x: f64, track_width: f64) -> f64 {
    (mouse_x - slider_x - thumb_width)
        .max(0.0)
        .min(track_width - thumb_width)
}

fn calculate_val(thumb_x: f64, min: f64, max: f64, thumb_width: f64, track_width: f64) -> f64 {
    thumb_x / (track_width - thumb_width) * (max - min)
}

fn calculate_thumb_x_from_val(
    val: f64,
    min: f64,
    max: f64,
    track_width: f64,
    thumb_width: f64,
) -> f64 {
    (val / (max - min)) * (track_width - thumb_width)
}

// --- Helpers --

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

    const ERROR: f64 = f64::EPSILON;

    #[test]
    fn test_calculate_thumb_x() {
        assert!((0.0 - calculate_thumb_x(-1000.0, 32.0, 0.0, 100.0)).abs() < ERROR);
        assert!((0.0 - calculate_thumb_x(0.0, 32.0, 0.0, 100.0)).abs() < ERROR);
        assert!((18.0 - calculate_thumb_x(50.0, 32.0, 0.0, 100.0)).abs() < ERROR);
        assert!((36.0 - calculate_thumb_x(68.0, 32.0, 0.0, 100.0)).abs() < ERROR);
        assert!((68.0 - calculate_thumb_x(100.0, 32.0, 0.0, 100.0)).abs() < ERROR);
        assert!((68.0 - calculate_thumb_x(1000.0, 32.0, 0.0, 100.0)).abs() < ERROR);
    }

    #[test]
    fn test_calculate_val() {
        assert!((0.0 - calculate_val(0.0, 0.0, 100.0, 32.0, 100.0)).abs() < ERROR);
        assert!((50.0 - calculate_val(34.0, 0.0, 100.0, 32.0, 100.0)).abs() < ERROR);
        assert!((100.0 - calculate_val(68.0, 0.0, 100.0, 32.0, 100.0)).abs() < ERROR);
        assert!((0.0 - calculate_val(0.0, -50.0, 50.0, 32.0, 100.0)).abs() < ERROR);
        assert!((50.0 - calculate_val(34.0, -50.0, 50.0, 32.0, 100.0)).abs() < ERROR);
        assert!((100.0 - calculate_val(68.0, -50.0, 50.0, 32.0, 100.0)).abs() < ERROR);
    }

    #[test]
    fn test_adjust_val() {
        assert!((0.0 - adjust_val(-10.0, 0.0, 100.0)).abs() < ERROR);
        assert!((10.0 - adjust_val(10.0, 0.0, 100.0)).abs() < ERROR);
        assert!((100.0 - adjust_val(500.0, 0.0, 100.0)).abs() < ERROR);
    }

    #[test]
    fn test_adjust_min() {
        assert!((0.0 - adjust_min(0.0, 100.0)).abs() < ERROR);
        assert!((5.0 - adjust_min(5.0, 100.0)).abs() < ERROR);
        assert!((100.0 - adjust_min(500.0, 100.0)).abs() < ERROR);
    }

    #[test]
    fn test_adjust_max() {
        assert!((100.0 - adjust_max(0.0, 100.0)).abs() < ERROR);
        assert!((100.0 - adjust_max(100.0, 5.0)).abs() < ERROR);
        assert!((100.0 - adjust_max(0.0, 100.0)).abs() < ERROR);
    }

    #[test]
    fn test_calculate_thumb_x_from_val() {
        assert!((0.0 - calculate_thumb_x_from_val(0.0, 0.0, 100.0, 100.0, 32.0)).abs() < ERROR);
        assert!((34.0 - calculate_thumb_x_from_val(50.0, 0.0, 100.0, 100.0, 32.0)).abs() < ERROR);
        assert!((68.0 - calculate_thumb_x_from_val(100.0, 0.0, 100.0, 100.0, 32.0)).abs() < ERROR);
    }
}
<|endoftext|>


<commit_before>// lock-free stack
use std::fmt::{self, Debug};
use std::ptr;
use std::ops::Deref;
use std::sync::atomic::Ordering::{Relaxed, SeqCst};

use epoch::{Atomic, Guard, Owned, Shared, pin, unprotected};

use debug_delay;

/// A node in the lock-free `Stack`.
#[derive(Debug)]
pub struct Node<T: Send + 'static> {
    inner: T,
    next: Atomic<Node<T>>,
}

impl<T: Send + 'static> Drop for Node<T> {
    fn drop(&mut self) {
        unsafe {
            let next = self.next.load(Relaxed, unprotected()).as_raw();
            if !next.is_null() {
                drop(Box::from_raw(next as *mut Node<T>));
            }
        }
    }
}

/// A simple lock-free stack, with the ability to atomically
/// append or entirely swap-out entries.
pub struct Stack<T: Send + 'static> {
    head: Atomic<Node<T>>,
}

impl<T: Send + 'static> Default for Stack<T> {
    fn default() -> Stack<T> {
        Stack {
            head: Atomic::null(),
        }
    }
}

impl<T: Send + 'static> Drop for Stack<T> {
    fn drop(&mut self) {
        unsafe {
            let curr = self.head.load(Relaxed, unprotected()).as_raw();
            if !curr.is_null() {
                drop(Box::from_raw(curr as *mut Node<T>));
            }
        }
    }
}

impl<T> Debug for Stack<T>
    where T: Debug + Send + 'static + Sync
{
    fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
        let guard = pin();
        let head = self.head(&guard);
        let iter = StackIter::from_ptr(head, &guard);

        formatter.write_str("Stack [")?;
        let mut written = false;
        for node in iter {
            if written {
                formatter.write_str(", ")?;
            }
            formatter.write_str(&*format!("({:?}) ", &node as *const _))?;
            node.fmt(formatter)?;
            written = true;
        }
        formatter.write_str("]")?;
        Ok(())
    }
}

impl<T: Send + 'static> Deref for Node<T> {
    type Target = T;
    fn deref(&self) -> &T {
        &self.inner
    }
}

impl<T: Send + 'static> Stack<T> {
    /// Add an item to the stack, spinning until successful.
    pub fn push(&self, inner: T) {
        debug_delay();
        let node = Owned::new(Node {
            inner: inner,
            next: Atomic::null(),
        });

        unsafe {
            let node = node.into_shared(unprotected());

            loop {
                let head = self.head(unprotected());
                node.deref().next.store(head, SeqCst);
                if self.head
                    .compare_and_set(head, node, SeqCst, unprotected())
                    .is_ok()
                {
                    return;
                }
            }
        }
    }

    /// Pop the next item off the stack. Returns None if nothing is there.
    pub fn pop(&self) -> Option<T> {
        debug_delay();
        let guard = pin();
        let mut head = self.head(&guard);
        loop {
            match unsafe { head.as_ref() } {
                Some(h) => {
                    let next = h.next.load(SeqCst, &guard);
                    match self.head.compare_and_set(
                        head,
                        next,
                        SeqCst,
                        &guard,
                    ) {
                        Ok(_) => unsafe {
                            guard.defer(move || {
                                let head: *mut Node<T> = Box::into_raw(head.into_owned().into());
                                drop(Vec::from_raw_parts(head, 0, 1));
                            });
                            return Some(ptr::read(&h.inner));
                        },
                        Err(h) => head = h.current,
                    }
                }
                None => return None,
            }
        }
    }

    /// compare and push
    pub fn cap<'g>(
        &self,
        old: Shared<Node<T>>,
        new: T,
        guard: &'g Guard,
    ) -> Result<Shared<'g, Node<T>>, Shared<'g, Node<T>>> {
        debug_delay();
        let node = Owned::new(Node {
            inner: new,
            next: Atomic::null(),
        });

        node.next.store(old, SeqCst);

        let node = node.into_shared(guard);

        let res = self.head.compare_and_set(old, node, SeqCst, guard);
        if res.is_err() {
            unsafe {
                node.deref().next.store(Shared::null(), SeqCst);
                guard.defer(move || node.into_owned());
            }
            Err(res.unwrap_err().current)
        } else {
            Ok(node)
        }
    }

    /// attempt consolidation
    pub fn cas<'g>(
        &self,
        old: Shared<'g, Node<T>>,
        new: Shared<'g, Node<T>>,
        guard: &'g Guard,
    ) -> Result<Shared<'g, Node<T>>, Shared<'g, Node<T>>> {
        debug_delay();
        let res = self.head.compare_and_set(old, new, SeqCst, guard);
        if res.is_ok() {
            if !old.is_null() {
                unsafe { guard.defer(move || old.into_owned()) };
            }
            Ok(new)
        } else {
            if !new.is_null() {
                unsafe { guard.defer(move || new.into_owned()) };
            }

            Err(res.unwrap_err().current)
        }
    }

    /// Returns the current head pointer of the stack, which can
    /// later be used as the key for cas and cap operations.
    pub fn head<'g>(&self, guard: &'g Guard) -> Shared<'g, Node<T>> {
        self.head.load(SeqCst, guard)
    }
}

/// An iterator over nodes in a lock-free stack.
pub struct StackIter<'a, T>
    where T: 'a + Send + 'static + Sync
{
    inner: Shared<'a, Node<T>>,
    guard: &'a Guard,
}

impl<'a, T> StackIter<'a, T>
    where T: 'a + Send + 'static + Sync
{
    /// Creates a StackIter from a pointer to one.
    pub fn from_ptr<'b>(
        ptr: Shared<'b, Node<T>>,
        guard: &'b Guard,
    ) -> StackIter<'b, T> {
        StackIter {
            inner: ptr,
            guard: guard,
        }
    }
}

impl<'a, T> Iterator for StackIter<'a, T>
    where T: Send + 'static + Sync
{
    type Item = &'a T;
    fn next(&mut self) -> Option<Self::Item> {
        debug_delay();
        if self.inner.is_null() {
            None
        } else {
            unsafe {
                let ret = &self.inner.deref().inner;
                self.inner = self.inner.deref().next.load(SeqCst, self.guard);
                Some(ret)
            }
        }
    }
}

/// Turns a vector of elements into a lock-free stack
/// of them, and returns the head of the stack.
pub fn node_from_frag_vec<T>(from: Vec<T>) -> Owned<Node<T>>
    where T: Send + 'static + Sync
{
    let mut last = None;

    for item in from.into_iter().rev() {
        let node = Owned::new(Node {
            inner: item,
            next: Atomic::null(),
        });

        if let Some(last) = last {
            node.next.store(last, SeqCst);
        }

        last = Some(node);
    }

    last.unwrap()
}

#[test]
fn basic_functionality() {
    use std::thread;
    use std::sync::Arc;

    let ll = Arc::new(Stack::default());
    assert_eq!(ll.pop(), None);
    ll.push(1);
    let ll2 = Arc::clone(&ll);
    let t = thread::spawn(move || {
        ll2.push(2);
        ll2.push(3);
        ll2.push(4);
    });
    t.join().unwrap();
    ll.push(5);
    assert_eq!(ll.pop(), Some(5));
    assert_eq!(ll.pop(), Some(4));
    let ll3 = Arc::clone(&ll);
    let t = thread::spawn(move || {
        assert_eq!(ll3.pop(), Some(3));
        assert_eq!(ll3.pop(), Some(2));
    });
    t.join().unwrap();
    assert_eq!(ll.pop(), Some(1));
    let ll4 = Arc::clone(&ll);
    let t = thread::spawn(move || {
        assert_eq!(ll4.pop(), None);
    });
    t.join().unwrap();
}
<commit_msg>fix deferred dropping of stack heads during pop<commit_after>// lock-free stack
use std::fmt::{self, Debug};
use std::ptr;
use std::ops::Deref;
use std::sync::atomic::Ordering::{Relaxed, SeqCst};

use epoch::{Atomic, Guard, Owned, Shared, pin, unprotected};

use debug_delay;

/// A node in the lock-free `Stack`.
#[derive(Debug)]
pub struct Node<T: Send + 'static> {
    inner: T,
    next: Atomic<Node<T>>,
}

impl<T: Send + 'static> Drop for Node<T> {
    fn drop(&mut self) {
        unsafe {
            let next = self.next.load(Relaxed, unprotected()).as_raw();
            if !next.is_null() {
                drop(Box::from_raw(next as *mut Node<T>));
            }
        }
    }
}

/// A simple lock-free stack, with the ability to atomically
/// append or entirely swap-out entries.
pub struct Stack<T: Send + 'static> {
    head: Atomic<Node<T>>,
}

impl<T: Send + 'static> Default for Stack<T> {
    fn default() -> Stack<T> {
        Stack {
            head: Atomic::null(),
        }
    }
}

impl<T: Send + 'static> Drop for Stack<T> {
    fn drop(&mut self) {
        unsafe {
            let curr = self.head.load(Relaxed, unprotected()).as_raw();
            if !curr.is_null() {
                drop(Box::from_raw(curr as *mut Node<T>));
            }
        }
    }
}

impl<T> Debug for Stack<T>
    where T: Debug + Send + 'static + Sync
{
    fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
        let guard = pin();
        let head = self.head(&guard);
        let iter = StackIter::from_ptr(head, &guard);

        formatter.write_str("Stack [")?;
        let mut written = false;
        for node in iter {
            if written {
                formatter.write_str(", ")?;
            }
            formatter.write_str(&*format!("({:?}) ", &node as *const _))?;
            node.fmt(formatter)?;
            written = true;
        }
        formatter.write_str("]")?;
        Ok(())
    }
}

impl<T: Send + 'static> Deref for Node<T> {
    type Target = T;
    fn deref(&self) -> &T {
        &self.inner
    }
}

impl<T: Send + 'static> Stack<T> {
    /// Add an item to the stack, spinning until successful.
    pub fn push(&self, inner: T) {
        debug_delay();
        let node = Owned::new(Node {
            inner: inner,
            next: Atomic::null(),
        });

        unsafe {
            let node = node.into_shared(unprotected());

            loop {
                let head = self.head(unprotected());
                node.deref().next.store(head, SeqCst);
                if self.head
                    .compare_and_set(head, node, SeqCst, unprotected())
                    .is_ok()
                {
                    return;
                }
            }
        }
    }

    /// Pop the next item off the stack. Returns None if nothing is there.
    pub fn pop(&self) -> Option<T> {
        debug_delay();
        let guard = pin();
        let mut head = self.head(&guard);
        loop {
            match unsafe { head.as_ref() } {
                Some(h) => {
                    let next = h.next.load(SeqCst, &guard);
                    match self.head.compare_and_set(
                        head,
                        next,
                        SeqCst,
                        &guard,
                    ) {
                        Ok(_) => unsafe {
                            guard.defer(move || { head.into_owned(); });
                            return Some(ptr::read(&h.inner));
                        },
                        Err(h) => head = h.current,
                    }
                }
                None => return None,
            }
        }
    }

    /// compare and push
    pub fn cap<'g>(
        &self,
        old: Shared<Node<T>>,
        new: T,
        guard: &'g Guard,
    ) -> Result<Shared<'g, Node<T>>, Shared<'g, Node<T>>> {
        debug_delay();
        let node = Owned::new(Node {
            inner: new,
            next: Atomic::null(),
        });

        node.next.store(old, SeqCst);

        let node = node.into_shared(guard);

        let res = self.head.compare_and_set(old, node, SeqCst, guard);
        if res.is_err() {
            unsafe {
                node.deref().next.store(Shared::null(), SeqCst);
                guard.defer(move || node.into_owned());
            }
            Err(res.unwrap_err().current)
        } else {
            Ok(node)
        }
    }

    /// attempt consolidation
    pub fn cas<'g>(
        &self,
        old: Shared<'g, Node<T>>,
        new: Shared<'g, Node<T>>,
        guard: &'g Guard,
    ) -> Result<Shared<'g, Node<T>>, Shared<'g, Node<T>>> {
        debug_delay();
        let res = self.head.compare_and_set(old, new, SeqCst, guard);
        if res.is_ok() {
            if !old.is_null() {
                unsafe { guard.defer(move || old.into_owned()) };
            }
            Ok(new)
        } else {
            if !new.is_null() {
                unsafe { guard.defer(move || new.into_owned()) };
            }

            Err(res.unwrap_err().current)
        }
    }

    /// Returns the current head pointer of the stack, which can
    /// later be used as the key for cas and cap operations.
    pub fn head<'g>(&self, guard: &'g Guard) -> Shared<'g, Node<T>> {
        self.head.load(SeqCst, guard)
    }
}

/// An iterator over nodes in a lock-free stack.
pub struct StackIter<'a, T>
    where T: 'a + Send + 'static + Sync
{
    inner: Shared<'a, Node<T>>,
    guard: &'a Guard,
}

impl<'a, T> StackIter<'a, T>
    where T: 'a + Send + 'static + Sync
{
    /// Creates a StackIter from a pointer to one.
    pub fn from_ptr<'b>(
        ptr: Shared<'b, Node<T>>,
        guard: &'b Guard,
    ) -> StackIter<'b, T> {
        StackIter {
            inner: ptr,
            guard: guard,
        }
    }
}

impl<'a, T> Iterator for StackIter<'a, T>
    where T: Send + 'static + Sync
{
    type Item = &'a T;
    fn next(&mut self) -> Option<Self::Item> {
        debug_delay();
        if self.inner.is_null() {
            None
        } else {
            unsafe {
                let ret = &self.inner.deref().inner;
                self.inner = self.inner.deref().next.load(SeqCst, self.guard);
                Some(ret)
            }
        }
    }
}

/// Turns a vector of elements into a lock-free stack
/// of them, and returns the head of the stack.
pub fn node_from_frag_vec<T>(from: Vec<T>) -> Owned<Node<T>>
    where T: Send + 'static + Sync
{
    let mut last = None;

    for item in from.into_iter().rev() {
        let node = Owned::new(Node {
            inner: item,
            next: Atomic::null(),
        });

        if let Some(last) = last {
            node.next.store(last, SeqCst);
        }

        last = Some(node);
    }

    last.unwrap()
}

#[test]
fn basic_functionality() {
    use std::thread;
    use std::sync::Arc;

    let ll = Arc::new(Stack::default());
    assert_eq!(ll.pop(), None);
    ll.push(1);
    let ll2 = Arc::clone(&ll);
    let t = thread::spawn(move || {
        ll2.push(2);
        ll2.push(3);
        ll2.push(4);
    });
    t.join().unwrap();
    ll.push(5);
    assert_eq!(ll.pop(), Some(5));
    assert_eq!(ll.pop(), Some(4));
    let ll3 = Arc::clone(&ll);
    let t = thread::spawn(move || {
        assert_eq!(ll3.pop(), Some(3));
        assert_eq!(ll3.pop(), Some(2));
    });
    t.join().unwrap();
    assert_eq!(ll.pop(), Some(1));
    let ll4 = Arc::clone(&ll);
    let t = thread::spawn(move || {
        assert_eq!(ll4.pop(), None);
    });
    t.join().unwrap();
}
<|endoftext|>


<commit_before>fn showpresents(count: usize) {
    let days = ["second", "third", "fourth", "fifth", "sixth", "seventh", "eighth", "ninth",
                "tenth", "eleventh", "twelfth"];

    let presents = ["Two turtle doves",
                    "Three french hens",
                    "Four calling birds",
                    "Five golden rings",
                    "Six geese a-laying",
                    "Seven swans a-swimming",
                    "Eight maids a-milking",
                    "Nine ladies dancing",
                    "Ten lords a-leaping",
                    "Eleven pipers piping",
                    "Twelve drummers drumming"];

    println!("On the {} day of Christmas my true love gave to me {}",
             days[count - 1],
             presents[count - 1]);
    if count > 0 {
        let mut j = count - 1;
        while j > 0 {
            println!("{}", presents[j - 1]);
            j -= 1;

        }
    }
    println!("And a partridge in a pear tree \n");
}

fn main() {
    println!("On the first day of Christmas my true love gave to me a partridge in a pear tree\n");

    for count in 1..12 {
        showpresents(count);
    }
}
<commit_msg>Correct Twelve Days of Christmas Implementation<commit_after>fn main() {
    let days = ["first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth",
                "ninth", "tenth", "eleventh", "twelfth"];

    let gifts = ["A Patridge in a Pear Tree",
                 "Two Turtle Doves and",
                 "Three French Hens",
                 "Four Calling Birds",
                 "Five Golden Rings",
                 "Six Geese a Laying",
                 "Seven Swans a Swimming",
                 "Eight Maids a Milking",
                 "Nine Ladies Dancing",
                 "Ten Lords a Leaping",
                 "Eleven Pipers Piping",
                 "Twelve Drummers Drumming"];

    for i in 0..12 {
        println!("On the {} day of Christmas,", days[i]);
        println!("My true love sent to me:");

        for j in (0..i + 1).rev() {
            println!("{}", gifts[j]);
        }
        println!()
    }
}
<|endoftext|>


<commit_before>// Implements http://rosettacode.org/wiki/Hailstone_sequence
struct Hailstone {
  priv current: int,
       start:   int
}

impl Hailstone {
  fn new(n: int) -> Hailstone {
    Hailstone { current: n, start: n }
  }
}

impl Iterator<int> for Hailstone {
  fn next(&mut self) -> Option<int> {
    let current = self.current;
    match current {
      0               => {
        self.current = self.start;
        None
      },
      1               => {
        self.current = 0;
        Some(1)
      },
      x if x % 2 == 0 => {
        self.current = x / 2;
        Some(current)
      },
      x if x % 2 == 1 => {
        self.current = (3 * x) + 1;
        Some(current)
      },
      _               => None
    }
  }
}

fn main() {
  // Find the hailstone for 27.
  let two_seven: ~[int] = Hailstone::new(27).collect();
  println!("Testing: {}, Length: {}, Values: {}...{}", two_seven[0], two_seven.len(), two_seven.slice(0,4).to_str(), two_seven.slice(two_seven.len()-4, two_seven.len()).to_str());
  // Find the longest.
  let mut biggest = Hailstone::new(1); // Has size 0. :(
  for x in range(0, 100000) {
    let mut result = Hailstone::new(x);
    if result.len() > biggest.len() {
      biggest = result
    }
  };
  println!("Largest: {}", biggest.start);
}
<commit_msg>Fixed output.<commit_after>// Implements http://rosettacode.org/wiki/Hailstone_sequence
struct Hailstone {
  priv current: int,
       start:   int
}

impl Hailstone {
  fn new(n: int) -> Hailstone {
    Hailstone { current: n, start: n }
  }
}

impl Iterator<int> for Hailstone {
  fn next(&mut self) -> Option<int> {
    let current = self.current;
    match current {
      0               => {
        self.current = self.start;
        None
      },
      1               => {
        self.current = 0;
        Some(1)
      },
      x if x % 2 == 0 => {
        self.current = x / 2;
        Some(current)
      },
      x if x % 2 == 1 => {
        self.current = (3 * x) + 1;
        Some(current)
      },
      _               => None
    }
  }
}

fn main() {
  // Find the hailstone for 27.
  let two_seven: ~[int] = Hailstone::new(27).collect();
  println!("Testing: {}, Length: {}, Values: {}...{}", two_seven[0], two_seven.len(), two_seven.slice(0,4).to_str(), two_seven.slice(two_seven.len()-4, two_seven.len()).to_str());
  // Find the longest.
  let mut biggest = Hailstone::new(1); // Has size 0. :(
  for x in range(0, 100000) {
    let mut result = Hailstone::new(x);
    if result.len() > biggest.len() {
      biggest = result
    }
  };
  let size = biggest.len();
  println!("Largest: {}, Size: {}", biggest.start, size);
}
<|endoftext|>


<commit_before>//! RLPx protocol implementation in Rust

extern crate secp256k1;
extern crate rand;

extern crate sha3;
extern crate sha2;
extern crate byteorder;
extern crate crypto;
extern crate etcommon_bigint as bigint;
extern crate etcommon_crypto as hash;
extern crate etcommon_rlp as rlp;
extern crate etcommon_util;
extern crate bytes;
#[macro_use]
extern crate log;
#[macro_use]
extern crate futures;
extern crate tokio_io;
extern crate tokio_core;

mod util;
pub mod ecies;
mod peer;
mod mac;
mod errors;

pub use peer::{PeerStream, CapabilityInfo};

use bigint::H512;
use util::pk2id;
use hash::SECP256K1;
use secp256k1::key::{PublicKey, SecretKey};
use futures::future;
use futures::{Poll, Async, StartSend, AsyncSink, Future, Stream, Sink};
use std::io;
use std::net::SocketAddr;
use tokio_core::reactor::Handle;
use tokio_io::{AsyncRead, AsyncWrite};
use tokio_io::codec::{Framed, Encoder, Decoder};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
/// Sending node type specifying either all, any or a particular peer
pub enum RLPxNode {
    Any,
    All,
    Peer(H512),
}

/// Sending message for RLPx
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RLPxSendMessage {
    pub node: RLPxNode,
    pub capability: CapabilityInfo,
    pub id: usize,
    pub data: Vec<u8>,
}

/// Receiving message for RLPx
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RLPxReceiveMessage {
    Connected(H512),
    Disconnected(H512),
    Normal {
        node: H512,
        capability: CapabilityInfo,
        id: usize,
        data: Vec<u8>,
    }
}

/// A RLPx stream and sink
pub struct RLPxStream {
    streams: Vec<PeerStream>,
    futures: Vec<(H512, Box<Future<Item = PeerStream, Error = io::Error>>)>,
    newly_connected: Vec<H512>,
    newly_disconnected: Vec<H512>,
    active_peers: Vec<H512>,
    secret_key: SecretKey,
    protocol_version: usize,
    client_version: String,
    capabilities: Vec<CapabilityInfo>,
    port: u16,
    handle: Handle,
}

impl RLPxStream {
    /// Create a new RLPx stream
    pub fn new(handle: &Handle, secret_key: SecretKey, protocol_version: usize,
               client_version: String, capabilities: Vec<CapabilityInfo>,
               port: u16) -> RLPxStream {
        RLPxStream {
            streams: Vec::new(),
            futures: Vec::new(),
            secret_key, protocol_version, client_version,
            capabilities, port,
            handle: handle.clone(),
            active_peers: Vec::new(),
            newly_connected: Vec::new(),
            newly_disconnected: Vec::new(),
        }
    }

    /// Append a new peer to this RLPx stream if it does not exist
    pub fn add_peer(
        &mut self, addr: &SocketAddr, remote_id: H512
    ) {
        if !self.active_peers.contains(&remote_id) {
            let future = PeerStream::connect(addr, &self.handle, self.secret_key.clone(),
                                             remote_id, self.protocol_version,
                                             self.client_version.clone(),
                                             self.capabilities.clone(), self.port);
            self.futures.push((remote_id, future));
            self.active_peers.push(remote_id);
        }
    }

    /// Poll over new peers to resolve them to TCP streams
    pub fn poll_new_peers(&mut self) -> Poll<(), io::Error> {
        let ref mut futures = self.futures;
        let ref mut streams = self.streams;
        let ref mut active_peers = self.active_peers;
        let ref mut newly_connected = self.newly_connected;

        let mut all_ready = true;

        retain_mut(futures, |&mut (remote_id, ref mut future)| {
            match future.poll() {
                Ok(Async::NotReady) => {
                    all_ready = false;
                    true
                },
                Ok(Async::Ready(peer)) => {
                    streams.push(peer);
                    newly_connected.push(remote_id);
                    false
                },
                Err(e) => {
                    active_peers.retain(|peer_id| {
                        *peer_id != remote_id
                    });
                    false
                },
            }
        });

        if all_ready {
            Ok(Async::Ready(()))
        } else {
            Ok(Async::NotReady)
        }
    }

    /// Active peers
    pub fn active_peers(&self) -> &[H512] {
        self.active_peers.as_ref()
    }
}

fn retain_mut<T, F>(vec: &mut Vec<T>, mut f: F)
    where F: FnMut(&mut T) -> bool
{
    let len = vec.len();
    let mut del = 0;
    {
        let v = &mut **vec;

        for i in 0..len {
            if !f(&mut v[i]) {
                del += 1;
            } else if del > 0 {
                v.swap(i - del, i);
            }
        }
    }
    if del > 0 {
        vec.truncate(len - del);
    }
}

impl Stream for RLPxStream {
    type Item = RLPxReceiveMessage;
    type Error = io::Error;

    fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> {
        if self.newly_connected.len() > 0 {
            return Ok(Async::Ready(Some(RLPxReceiveMessage::Connected(self.newly_connected.pop().unwrap()))));
        }
        if self.newly_disconnected.len() > 0 {
            return Ok(Async::Ready(Some(RLPxReceiveMessage::Disconnected(self.newly_disconnected.pop().unwrap()))));
        }

        self.poll_new_peers()?;

        let ref mut streams = self.streams;
        let ref mut active_peers = self.active_peers;
        let ref mut newly_connected = self.newly_connected;
        let ref mut newly_disconnected = self.newly_disconnected;

        let mut ret: Option<Self::Item> = None;
        retain_mut(streams, |ref mut peer| {
            if ret.is_some() {
                return true;
            }

            let id = peer.remote_id();
            match peer.poll() {
                Ok(Async::NotReady) => true,
                Ok(Async::Ready(None)) => {
                    newly_disconnected.push(id);
                    false
                },
                Ok(Async::Ready(Some((cap, message_id, data)))) => {
                    ret = Some(RLPxReceiveMessage::Normal { node: id, capability: cap, id: message_id, data });
                    true
                },
                Err(e) => {
                    active_peers.retain(|peer_id| {
                        *peer_id != id
                    });
                    newly_disconnected.push(id);
                    false
                },
            }
        });

        if ret.is_some() {
            Ok(Async::Ready(ret))
        } else {
            if newly_connected.len() > 0 {
                return Ok(Async::Ready(Some(RLPxReceiveMessage::Connected(newly_connected.pop().unwrap()))));
            }
            if newly_disconnected.len() > 0 {
                return Ok(Async::Ready(Some(RLPxReceiveMessage::Disconnected(newly_disconnected.pop().unwrap()))));
            }
            Ok(Async::NotReady)
        }
    }
}

impl Sink for RLPxStream {
    type SinkItem = RLPxSendMessage;
    type SinkError = io::Error;

    fn start_send(&mut self, message: RLPxSendMessage) -> StartSend<Self::SinkItem, Self::SinkError> {
        self.poll_new_peers()?;

        let ref mut streams = self.streams;
        let ref mut active_peers = self.active_peers;
        let ref mut newly_disconnected = self.newly_disconnected;

        let mut any_ready = false;

        retain_mut(streams, |ref mut peer| {
            let id = peer.remote_id();

            if match message.node {
                RLPxNode::Peer(peer_id) => peer_id == id,
                RLPxNode::All => true,
                RLPxNode::Any => !any_ready,
            } {
                let remote_id = peer.remote_id();
                match peer.start_send((message.capability.clone(), message.id, message.data.clone())) {
                    Ok(AsyncSink::Ready) => {
                        any_ready = true;
                        true
                    },
                    Ok(AsyncSink::NotReady(_)) => true,
                    Err(e) => {
                        active_peers.retain(|peer_id| {
                            *peer_id != remote_id
                        });
                        newly_disconnected.push(remote_id);
                        false
                    },
                }
            } else {
                true
            }
        });

        if any_ready {
            Ok(AsyncSink::Ready)
        } else {
            Ok(AsyncSink::NotReady(message))
        }
    }

    fn poll_complete(&mut self) -> Poll<(), Self::SinkError> {
        let ref mut streams = self.streams;
        let ref mut active_peers = self.active_peers;
        let ref mut newly_disconnected = self.newly_disconnected;

        let mut all_ready = true;

        retain_mut(streams, |ref mut peer| {
            let remote_id = peer.remote_id();
            match peer.poll_complete() {
                Ok(Async::Ready(())) => true,
                Ok(Async::NotReady) => {
                    all_ready = false;
                    true
                },
                Err(e) => {
                    active_peers.retain(|peer_id| {
                        *peer_id != remote_id
                    });
                    newly_disconnected.push(remote_id);
                    false
                },
            }
        });

        if all_ready {
            Ok(Async::Ready(()))
        } else {
            Ok(Async::NotReady)
        }
    }
}

#[cfg(test)]
mod tests {
    #[test]
    fn it_works() {
    }
}
<commit_msg>rlpx: allow force disconnecting a peer<commit_after>//! RLPx protocol implementation in Rust

extern crate secp256k1;
extern crate rand;

extern crate sha3;
extern crate sha2;
extern crate byteorder;
extern crate crypto;
extern crate etcommon_bigint as bigint;
extern crate etcommon_crypto as hash;
extern crate etcommon_rlp as rlp;
extern crate etcommon_util;
extern crate bytes;
#[macro_use]
extern crate log;
#[macro_use]
extern crate futures;
extern crate tokio_io;
extern crate tokio_core;

mod util;
pub mod ecies;
mod peer;
mod mac;
mod errors;

pub use peer::{PeerStream, CapabilityInfo};

use bigint::H512;
use util::pk2id;
use hash::SECP256K1;
use secp256k1::key::{PublicKey, SecretKey};
use futures::future;
use futures::{Poll, Async, StartSend, AsyncSink, Future, Stream, Sink};
use std::io;
use std::net::SocketAddr;
use tokio_core::reactor::Handle;
use tokio_io::{AsyncRead, AsyncWrite};
use tokio_io::codec::{Framed, Encoder, Decoder};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
/// Sending node type specifying either all, any or a particular peer
pub enum RLPxNode {
    Any,
    All,
    Peer(H512),
}

/// Sending message for RLPx
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RLPxSendMessage {
    pub node: RLPxNode,
    pub capability: CapabilityInfo,
    pub id: usize,
    pub data: Vec<u8>,
}

/// Receiving message for RLPx
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RLPxReceiveMessage {
    Connected(H512),
    Disconnected(H512),
    Normal {
        node: H512,
        capability: CapabilityInfo,
        id: usize,
        data: Vec<u8>,
    }
}

/// A RLPx stream and sink
pub struct RLPxStream {
    streams: Vec<PeerStream>,
    futures: Vec<(H512, Box<Future<Item = PeerStream, Error = io::Error>>)>,
    newly_connected: Vec<H512>,
    newly_disconnected: Vec<H512>,
    active_peers: Vec<H512>,
    secret_key: SecretKey,
    protocol_version: usize,
    client_version: String,
    capabilities: Vec<CapabilityInfo>,
    port: u16,
    handle: Handle,
}

impl RLPxStream {
    /// Create a new RLPx stream
    pub fn new(handle: &Handle, secret_key: SecretKey, protocol_version: usize,
               client_version: String, capabilities: Vec<CapabilityInfo>,
               port: u16) -> RLPxStream {
        RLPxStream {
            streams: Vec::new(),
            futures: Vec::new(),
            secret_key, protocol_version, client_version,
            capabilities, port,
            handle: handle.clone(),
            active_peers: Vec::new(),
            newly_connected: Vec::new(),
            newly_disconnected: Vec::new(),
        }
    }

    /// Append a new peer to this RLPx stream if it does not exist
    pub fn add_peer(
        &mut self, addr: &SocketAddr, remote_id: H512
    ) {
        if !self.active_peers.contains(&remote_id) {
            let future = PeerStream::connect(addr, &self.handle, self.secret_key.clone(),
                                             remote_id, self.protocol_version,
                                             self.client_version.clone(),
                                             self.capabilities.clone(), self.port);
            self.futures.push((remote_id, future));
            self.active_peers.push(remote_id);
        }
    }

    /// Force disconnecting a peer if it is already connected or about
    /// to be connected. Useful for removing peers on a different hard
    /// fork network
    pub fn disconnect_peer(&mut self, remote_id: H512) {
        let ref mut futures = self.futures;
        let ref mut streams = self.streams;
        let ref mut newly_disconnected = self.newly_disconnected;

        retain_mut(streams, |peer| {
            if peer.remote_id() == remote_id {
                newly_disconnected.push(remote_id);
                false
            } else {
                true
            }
        });

        retain_mut(futures, |&mut (peer_id, _)| {
            peer_id != remote_id
        });
    }

    /// Poll over new peers to resolve them to TCP streams
    pub fn poll_new_peers(&mut self) -> Poll<(), io::Error> {
        let ref mut futures = self.futures;
        let ref mut streams = self.streams;
        let ref mut active_peers = self.active_peers;
        let ref mut newly_connected = self.newly_connected;

        let mut all_ready = true;

        retain_mut(futures, |&mut (remote_id, ref mut future)| {
            match future.poll() {
                Ok(Async::NotReady) => {
                    all_ready = false;
                    true
                },
                Ok(Async::Ready(peer)) => {
                    streams.push(peer);
                    newly_connected.push(remote_id);
                    false
                },
                Err(e) => {
                    active_peers.retain(|peer_id| {
                        *peer_id != remote_id
                    });
                    false
                },
            }
        });

        if all_ready {
            Ok(Async::Ready(()))
        } else {
            Ok(Async::NotReady)
        }
    }

    /// Active peers
    pub fn active_peers(&self) -> &[H512] {
        self.active_peers.as_ref()
    }
}

fn retain_mut<T, F>(vec: &mut Vec<T>, mut f: F)
    where F: FnMut(&mut T) -> bool
{
    let len = vec.len();
    let mut del = 0;
    {
        let v = &mut **vec;

        for i in 0..len {
            if !f(&mut v[i]) {
                del += 1;
            } else if del > 0 {
                v.swap(i - del, i);
            }
        }
    }
    if del > 0 {
        vec.truncate(len - del);
    }
}

impl Stream for RLPxStream {
    type Item = RLPxReceiveMessage;
    type Error = io::Error;

    fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> {
        if self.newly_connected.len() > 0 {
            return Ok(Async::Ready(Some(RLPxReceiveMessage::Connected(self.newly_connected.pop().unwrap()))));
        }
        if self.newly_disconnected.len() > 0 {
            return Ok(Async::Ready(Some(RLPxReceiveMessage::Disconnected(self.newly_disconnected.pop().unwrap()))));
        }

        self.poll_new_peers()?;

        let ref mut streams = self.streams;
        let ref mut active_peers = self.active_peers;
        let ref mut newly_connected = self.newly_connected;
        let ref mut newly_disconnected = self.newly_disconnected;

        let mut ret: Option<Self::Item> = None;
        retain_mut(streams, |ref mut peer| {
            if ret.is_some() {
                return true;
            }

            let id = peer.remote_id();
            match peer.poll() {
                Ok(Async::NotReady) => true,
                Ok(Async::Ready(None)) => {
                    newly_disconnected.push(id);
                    false
                },
                Ok(Async::Ready(Some((cap, message_id, data)))) => {
                    ret = Some(RLPxReceiveMessage::Normal { node: id, capability: cap, id: message_id, data });
                    true
                },
                Err(e) => {
                    active_peers.retain(|peer_id| {
                        *peer_id != id
                    });
                    newly_disconnected.push(id);
                    false
                },
            }
        });

        if ret.is_some() {
            Ok(Async::Ready(ret))
        } else {
            if newly_connected.len() > 0 {
                return Ok(Async::Ready(Some(RLPxReceiveMessage::Connected(newly_connected.pop().unwrap()))));
            }
            if newly_disconnected.len() > 0 {
                return Ok(Async::Ready(Some(RLPxReceiveMessage::Disconnected(newly_disconnected.pop().unwrap()))));
            }
            Ok(Async::NotReady)
        }
    }
}

impl Sink for RLPxStream {
    type SinkItem = RLPxSendMessage;
    type SinkError = io::Error;

    fn start_send(&mut self, message: RLPxSendMessage) -> StartSend<Self::SinkItem, Self::SinkError> {
        self.poll_new_peers()?;

        let ref mut streams = self.streams;
        let ref mut active_peers = self.active_peers;
        let ref mut newly_disconnected = self.newly_disconnected;

        let mut any_ready = false;

        retain_mut(streams, |ref mut peer| {
            let id = peer.remote_id();

            if match message.node {
                RLPxNode::Peer(peer_id) => peer_id == id,
                RLPxNode::All => true,
                RLPxNode::Any => !any_ready,
            } {
                let remote_id = peer.remote_id();
                match peer.start_send((message.capability.clone(), message.id, message.data.clone())) {
                    Ok(AsyncSink::Ready) => {
                        any_ready = true;
                        true
                    },
                    Ok(AsyncSink::NotReady(_)) => true,
                    Err(e) => {
                        active_peers.retain(|peer_id| {
                            *peer_id != remote_id
                        });
                        newly_disconnected.push(remote_id);
                        false
                    },
                }
            } else {
                true
            }
        });

        if any_ready {
            Ok(AsyncSink::Ready)
        } else {
            Ok(AsyncSink::NotReady(message))
        }
    }

    fn poll_complete(&mut self) -> Poll<(), Self::SinkError> {
        let ref mut streams = self.streams;
        let ref mut active_peers = self.active_peers;
        let ref mut newly_disconnected = self.newly_disconnected;

        let mut all_ready = true;

        retain_mut(streams, |ref mut peer| {
            let remote_id = peer.remote_id();
            match peer.poll_complete() {
                Ok(Async::Ready(())) => true,
                Ok(Async::NotReady) => {
                    all_ready = false;
                    true
                },
                Err(e) => {
                    active_peers.retain(|peer_id| {
                        *peer_id != remote_id
                    });
                    newly_disconnected.push(remote_id);
                    false
                },
            }
        });

        if all_ready {
            Ok(Async::Ready(()))
        } else {
            Ok(Async::NotReady)
        }
    }
}

#[cfg(test)]
mod tests {
    #[test]
    fn it_works() {
    }
}
<|endoftext|>


<commit_before>use std::fs::File;
use std::io::{self, BufRead};
use std::path::Path;
use regex::Regex;

#[macro_use]
extern crate lazy_static;
pub fn get_number<P: AsRef<Path>>(filename: P) -> io::Result<u32> {
    lazy_static! {
        static ref RE: Regex = Regex::new(r"NUMBER=(\d+)").unwrap();
    }
    let mut matches = match_lines(filename, &RE)?;
    return Ok(matches.next().unwrap().parse().unwrap());
}

fn match_lines<P: AsRef<Path>>(filename: P, regex: &'static Regex) -> io::Result<impl Iterator<Item = String>> {
    let lines = read_lines(filename)?;
    let matches = lines.filter_map(move |line| regex.captures(&line).map(|captures| captures[1].to_string()));
    Ok(matches)
}

fn read_lines<P: AsRef<Path>>(filename: P) -> io::Result<impl Iterator<Item = String>> {
    let file = File::open(filename)?;
    return Ok(io::BufReader::new(file).lines().map(|line|
        line.unwrap()
    ));
}

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

    #[test]
    fn get_test_number() {
        assert_eq!(get_number("../data/test.txt").unwrap() , 3);
    }
}
<commit_msg>Works. Regex lifetime not correct yet<commit_after>use std::fs::File;
use std::io::{self, BufRead};
use std::path::Path;
use regex::Regex;

//#[macro_use]
//extern crate lazy_static;
pub fn get_number<P: AsRef<Path>>(filename: P) -> io::Result<u32> {
    /*
    lazy_static! {
        static ref RE: Regex = Regex::new(r"NUMBER=(\d+)").unwrap();
    }
    */
    //let RE: Regex = Regex::new(r"NUMBER=(\d+)").unwrap();
    let regex: Regex = Regex::new(r"OUTPUT:(.*)").unwrap();
    let mut matches = match_lines(filename, &regex)?;
    return Ok(matches.next().unwrap().parse().unwrap());
}

pub fn get_output<P: AsRef<Path>>(filename: P) -> io::Result<impl Iterator<Item = i32>> {
    let regex: Regex = Regex::new(r"OUTPUT:(.*)").unwrap();
    let matches = match_lines(filename, &regex)?;
    let values = matches.map(|s|
        s.split(',').map(|v| v.parse().unwrap()).collect::<Vec<_>>().into_iter()
    ).flatten();
    Ok(values)
}

fn captured(regex: &Regex, index: usize, line: &str) -> String {
    regex.captures(&line).unwrap()[index].to_string()
}

fn match_lines<P: AsRef<Path>>(filename: P, _regex: &Regex) -> io::Result<impl Iterator<Item = String>> {
    let lines = read_lines(filename)?;
    let matches = lines.filter_map(|line|
        //Some(captured(regex, &line))
        Some(captured(&Regex::new(r"NUMBER=(.*)").unwrap(), 1, &line))
    );
    Ok(matches)
}

fn read_lines<P: AsRef<Path>>(filename: P) -> io::Result<impl Iterator<Item = String>> {
    let file = File::open(filename)?;
    return Ok(io::BufReader::new(file).lines().map(|line|
        line.unwrap()
    ));
}

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

    #[test]
    fn test_captured() {
        let regex: Regex = Regex::new(r"OUTPUT:(\d+),(.*)").unwrap();
        assert_eq!(captured(&regex, 1, "OUTPUT:1231,"), "1231");
        assert_eq!(captured(&regex, 2, "OUTPUT:3234,rust"), "rust");
    }

    #[test]
    fn get_test_number() {
        assert_eq!(get_number("../data/test.txt").unwrap() , 3);
    }
}
<|endoftext|>


<commit_before>pub mod checksum;
pub mod emblem;

pub fn short_name(filename: Option<&str>, seconds: f64) -> Result<String, &'static str> {
  let multiplier: f64 = 40500000f64;
  let tick: u64 = (seconds * multiplier) as u64;

  match filename {
    Some(name) => {
      if name.len() < 18 {
        Ok(format!("fze1-{}.dat", name))
      } else {
        Err("emblem-filename should be 18 characters or less.")
      }
    },
    None => Ok(format!("fze0200002000{:14X}.dat", tick as u64))
  }
}

pub fn full_name(filename: Option<&str>) -> String {
  format!("8P-GFZE-{}.gci", filename.unwrap())
}
<commit_msg>full_name receives a string<commit_after>pub mod checksum;
pub mod emblem;

pub fn short_name(filename: Option<&str>, seconds: f64) -> Result<String, &'static str> {
  let multiplier: f64 = 40500000f64;
  let tick: u64 = (seconds * multiplier) as u64;

  match filename {
    Some(name) => {
      if name.len() < 18 {
        Ok(format!("fze1-{}.dat", name))
      } else {
        Err("emblem-filename should be 18 characters or less.")
      }
    },
    None => Ok(format!("fze0200002000{:14X}.dat", tick as u64))
  }
}

pub fn full_name(filename: &str) -> String {
  format!("8P-GFZE-{}.gci", filename)
}
<|endoftext|>


<commit_before>#![feature(plugin, custom_derive)]
#![plugin(rocket_codegen)]

extern crate rocket;

use rocket::request::Form;

#[derive(FromForm)]
struct FormData {
    form_data: String,
}

#[patch("/", data = "<form_data>")]
fn bug(form_data: Form<FormData>) -> &'static str {
    assert_eq!("Form data", &form_data.get().form_data);
    "OK"
}

use rocket::testing::MockRequest;
use rocket::http::Method::*;
use rocket::http::ContentType;

#[test]
fn method_eval() {
    let rocket = rocket::ignite().mount("/", routes![bug]);

    let mut req = MockRequest::new(Patch, "/")
        .header(ContentType::Form)
        .body("_method=patch&form_data=Form+data");

    let mut response = req.dispatch_with(&rocket);
    let body_str = response.body().and_then(|b| b.into_string());
    assert_eq!(body_str, Some("OK".to_string()));
}
<commit_msg>Remove unnecessary new line.<commit_after>#![feature(plugin, custom_derive)]
#![plugin(rocket_codegen)]

extern crate rocket;

use rocket::request::Form;

#[derive(FromForm)]
struct FormData {
    form_data: String,
}

#[patch("/", data = "<form_data>")]
fn bug(form_data: Form<FormData>) -> &'static str {
    assert_eq!("Form data", &form_data.get().form_data);
    "OK"
}

use rocket::testing::MockRequest;
use rocket::http::Method::*;
use rocket::http::ContentType;

#[test]
fn method_eval() {
    let rocket = rocket::ignite().mount("/", routes![bug]);

    let mut req = MockRequest::new(Patch, "/")
        .header(ContentType::Form)
        .body("_method=patch&form_data=Form+data");

    let mut response = req.dispatch_with(&rocket);
    let body_str = response.body().and_then(|b| b.into_string());
    assert_eq!(body_str, Some("OK".to_string()));
}
<|endoftext|>


<commit_before>// Automatically generated rust module for 'no_std.proto' file

#![allow(non_snake_case)]
#![allow(non_upper_case_globals)]
#![allow(non_camel_case_types)]
#![allow(unused_imports)]
#![allow(unknown_lints)]
#![allow(clippy)]
#![cfg_attr(rustfmt, rustfmt_skip)]

use quick_protobuf::{MessageRead, MessageWrite, BytesReader, Writer, WriterBackend, Result};
use quick_protobuf::sizeofs::*;
use super::super::*;

#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum MyEnum {
    Val0 = 0,
    Val1 = 1,
}

impl Default for MyEnum {
    fn default() -> Self {
        MyEnum::Val0
    }
}

impl From<i32> for MyEnum {
    fn from(i: i32) -> Self {
        match i {
            0 => MyEnum::Val0,
            1 => MyEnum::Val1,
            _ => Self::default(),
        }
    }
}

impl<'a> From<&'a str> for MyEnum {
    fn from(s: &'a str) -> Self {
        match s {
            "Val0" => MyEnum::Val0,
            "Val1" => MyEnum::Val1,
            _ => Self::default(),
        }
    }
}

#[derive(Debug, Default, PartialEq, Clone)]
pub struct EmbeddedMessage {
    pub val: i32,
    pub e: protos::no_std::MyEnum,
}

impl<'a> MessageRead<'a> for EmbeddedMessage {
    fn from_reader(r: &mut BytesReader, bytes: &'a [u8]) -> Result<Self> {
        let mut msg = Self::default();
        while !r.is_eof() {
            match r.next_tag(bytes) {
                Ok(8) => msg.val = r.read_int32(bytes)?,
                Ok(16) => msg.e = r.read_enum(bytes)?,
                Ok(t) => { r.read_unknown(bytes, t)?; }
                Err(e) => return Err(e),
            }
        }
        Ok(msg)
    }
}

impl MessageWrite for EmbeddedMessage {
    fn get_size(&self) -> usize {
        0
        + if self.val == 0i32 { 0 } else { 1 + sizeof_varint(*(&self.val) as u64) }
        + if self.e == protos::no_std::MyEnum::Val0 { 0 } else { 1 + sizeof_varint(*(&self.e) as u64) }
    }

    fn write_message<W: WriterBackend>(&self, w: &mut Writer<W>) -> Result<()> {
        if self.val != 0i32 { w.write_with_tag(8, |w| w.write_int32(*&self.val))?; }
        if self.e != protos::no_std::MyEnum::Val0 { w.write_with_tag(16, |w| w.write_enum(*&self.e as i32))?; }
        Ok(())
    }
}

#[derive(Debug, Default, PartialEq, Clone)]
pub struct NoStdMessage {
    pub num: u32,
    pub nums: arrayvec::ArrayVec<[u32; 16]>,
    pub message: Option<protos::no_std::EmbeddedMessage>,
    pub messages: arrayvec::ArrayVec<[protos::no_std::EmbeddedMessage; 16]>,
}

impl<'a> MessageRead<'a> for NoStdMessage {
    fn from_reader(r: &mut BytesReader, bytes: &'a [u8]) -> Result<Self> {
        let mut msg = Self::default();
        while !r.is_eof() {
            match r.next_tag(bytes) {
                Ok(13) => msg.num = r.read_fixed32(bytes)?,
                Ok(18) => msg.nums = r.read_packed_arrayvec(bytes, |r, bytes| Ok(r.read_fixed32(bytes)?))?,
                Ok(26) => msg.message = Some(r.read_message::<protos::no_std::EmbeddedMessage>(bytes)?),
                Ok(34) => msg.messages.push(r.read_message::<protos::no_std::EmbeddedMessage>(bytes)?),
                Ok(t) => { r.read_unknown(bytes, t)?; }
                Err(e) => return Err(e),
            }
        }
        Ok(msg)
    }
}

impl MessageWrite for NoStdMessage {
    fn get_size(&self) -> usize {
        0
        + if self.num == 0u32 { 0 } else { 1 + 4 }
        + if self.nums.is_empty() { 0 } else { 1 + sizeof_len(self.nums.len() * 4) }
        + self.message.as_ref().map_or(0, |m| 1 + sizeof_len((m).get_size()))
        + self.messages.iter().map(|s| 1 + sizeof_len((s).get_size())).sum::<usize>()
    }

    fn write_message<W: WriterBackend>(&self, w: &mut Writer<W>) -> Result<()> {
        if self.num != 0u32 { w.write_with_tag(13, |w| w.write_fixed32(*&self.num))?; }
        w.write_packed_fixed_with_tag(18, &self.nums)?;
        if let Some(ref s) = self.message { w.write_with_tag(26, |w| w.write_message(s))?; }
        for s in &self.messages { w.write_with_tag(34, |w| w.write_message(s))?; }
        Ok(())
    }
}

<commit_msg>regenerate nostd test proto<commit_after>// Automatically generated rust module for 'no_std.proto' file

#![allow(non_snake_case)]
#![allow(non_upper_case_globals)]
#![allow(non_camel_case_types)]
#![allow(unused_imports)]
#![allow(unknown_lints)]
#![allow(clippy)]
#![cfg_attr(rustfmt, rustfmt_skip)]

extern crate alloc;
use alloc::vec::Vec;
use quick_protobuf::{MessageRead, MessageWrite, BytesReader, Writer, WriterBackend, Result};
use quick_protobuf::sizeofs::*;
use super::super::*;

#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum MyEnum {
    Val0 = 0,
    Val1 = 1,
}

impl Default for MyEnum {
    fn default() -> Self {
        MyEnum::Val0
    }
}

impl From<i32> for MyEnum {
    fn from(i: i32) -> Self {
        match i {
            0 => MyEnum::Val0,
            1 => MyEnum::Val1,
            _ => Self::default(),
        }
    }
}

impl<'a> From<&'a str> for MyEnum {
    fn from(s: &'a str) -> Self {
        match s {
            "Val0" => MyEnum::Val0,
            "Val1" => MyEnum::Val1,
            _ => Self::default(),
        }
    }
}

#[derive(Debug, Default, PartialEq, Clone)]
pub struct EmbeddedMessage {
    pub val: i32,
    pub e: protos::no_std::MyEnum,
}

impl<'a> MessageRead<'a> for EmbeddedMessage {
    fn from_reader(r: &mut BytesReader, bytes: &'a [u8]) -> Result<Self> {
        let mut msg = Self::default();
        while !r.is_eof() {
            match r.next_tag(bytes) {
                Ok(8) => msg.val = r.read_int32(bytes)?,
                Ok(16) => msg.e = r.read_enum(bytes)?,
                Ok(t) => { r.read_unknown(bytes, t)?; }
                Err(e) => return Err(e),
            }
        }
        Ok(msg)
    }
}

impl MessageWrite for EmbeddedMessage {
    fn get_size(&self) -> usize {
        0
        + if self.val == 0i32 { 0 } else { 1 + sizeof_varint(*(&self.val) as u64) }
        + if self.e == protos::no_std::MyEnum::Val0 { 0 } else { 1 + sizeof_varint(*(&self.e) as u64) }
    }

    fn write_message<W: WriterBackend>(&self, w: &mut Writer<W>) -> Result<()> {
        if self.val != 0i32 { w.write_with_tag(8, |w| w.write_int32(*&self.val))?; }
        if self.e != protos::no_std::MyEnum::Val0 { w.write_with_tag(16, |w| w.write_enum(*&self.e as i32))?; }
        Ok(())
    }
}

#[derive(Debug, Default, PartialEq, Clone)]
pub struct NoStdMessage<'a> {
    pub num: u32,
    pub nums: Cow<'a, [u32]>,
    pub message: Option<protos::no_std::EmbeddedMessage>,
    pub messages: Vec<protos::no_std::EmbeddedMessage>,
}

impl<'a> MessageRead<'a> for NoStdMessage<'a> {
    fn from_reader(r: &mut BytesReader, bytes: &'a [u8]) -> Result<Self> {
        let mut msg = Self::default();
        while !r.is_eof() {
            match r.next_tag(bytes) {
                Ok(13) => msg.num = r.read_fixed32(bytes)?,
                Ok(18) => msg.nums = r.read_packed_fixed(bytes)?.into(),
                Ok(26) => msg.message = Some(r.read_message::<protos::no_std::EmbeddedMessage>(bytes)?),
                Ok(34) => msg.messages.push(r.read_message::<protos::no_std::EmbeddedMessage>(bytes)?),
                Ok(t) => { r.read_unknown(bytes, t)?; }
                Err(e) => return Err(e),
            }
        }
        Ok(msg)
    }
}

impl<'a> MessageWrite for NoStdMessage<'a> {
    fn get_size(&self) -> usize {
        0
        + if self.num == 0u32 { 0 } else { 1 + 4 }
        + if self.nums.is_empty() { 0 } else { 1 + sizeof_len(self.nums.len() * 4) }
        + self.message.as_ref().map_or(0, |m| 1 + sizeof_len((m).get_size()))
        + self.messages.iter().map(|s| 1 + sizeof_len((s).get_size())).sum::<usize>()
    }

    fn write_message<W: WriterBackend>(&self, w: &mut Writer<W>) -> Result<()> {
        if self.num != 0u32 { w.write_with_tag(13, |w| w.write_fixed32(*&self.num))?; }
        w.write_packed_fixed_with_tag(18, &self.nums)?;
        if let Some(ref s) = self.message { w.write_with_tag(26, |w| w.write_message(s))?; }
        for s in &self.messages { w.write_with_tag(34, |w| w.write_message(s))?; }
        Ok(())
    }
}

<|endoftext|>


<commit_before>use crate::sys::time;

#[inline]
pub(super) fn monotonize(raw: time::Instant) -> time::Instant {
    inner::monotonize(raw)
}

#[cfg(all(target_has_atomic = "64", not(target_has_atomic = "128")))]
pub mod inner {
    use crate::sync::atomic::AtomicU64;
    use crate::sync::atomic::Ordering::*;
    use crate::sys::time;
    use crate::time::Duration;

    pub(in crate::time) const ZERO: time::Instant = time::Instant::zero();

    // bits 30 and 31 are never used since the nanoseconds part never exceeds 10^9
    const UNINITIALIZED: u64 = 0b11 << 30;
    static MONO: AtomicU64 = AtomicU64::new(UNINITIALIZED);

    #[inline]
    pub(super) fn monotonize(raw: time::Instant) -> time::Instant {
        monotonize_impl(&MONO, raw)
    }

    #[inline]
    pub(in crate::time) fn monotonize_impl(mono: &AtomicU64, raw: time::Instant) -> time::Instant {
        let delta = raw.checked_sub_instant(&ZERO).unwrap();
        let secs = delta.as_secs();
        // occupies no more than 30 bits (10^9 seconds)
        let nanos = delta.subsec_nanos() as u64;

        // This wraps around every 136 years (2^32 seconds).
        // To detect backsliding we use wrapping arithmetic and declare forward steps smaller
        // than 2^31 seconds as expected and everything else as a backslide which will be
        // monotonized.
        // This could be a problem for programs that call instants at intervals greater
        // than 68 years. Interstellar probes may want to ensure that actually_monotonic() is true.
        let packed = (secs << 32) | nanos;
        let updated = mono.fetch_update(Relaxed, Relaxed, |old| {
            (old == UNINITIALIZED || packed.wrapping_sub(old) < u64::MAX / 2).then_some(packed)
        });
        match updated {
            Ok(_) => raw,
            Err(newer) => {
                // Backslide occurred. We reconstruct monotonized time from the upper 32 bit of the
                // passed in value and the 64bits loaded from the atomic
                let seconds_lower = newer >> 32;
                let mut seconds_upper = secs & 0xffff_ffff_0000_0000;
                if secs & 0xffff_ffff > seconds_lower {
                    // Backslide caused the lower 32bit of the seconds part to wrap.
                    // This must be the case because the seconds part is larger even though
                    // we are in the backslide branch, i.e. the seconds count should be smaller or equal.
                    //
                    // We assume that backslides are smaller than 2^32 seconds
                    // which means we need to add 1 to the upper half to restore it.
                    //
                    // Example:
                    // most recent observed time: 0xA1_0000_0000_0000_0000u128
                    // bits stored in AtomicU64:     0x0000_0000_0000_0000u64
                    // backslide by 1s
                    // caller time is             0xA0_ffff_ffff_0000_0000u128
                    // -> we can fix up the upper half time by adding 1 << 32
                    seconds_upper = seconds_upper.wrapping_add(0x1_0000_0000);
                }
                let secs = seconds_upper | seconds_lower;
                let nanos = newer as u32;
                ZERO.checked_add_duration(&Duration::new(secs, nanos)).unwrap()
            }
        }
    }
}

#[cfg(target_has_atomic = "128")]
pub mod inner {
    use crate::sync::atomic::AtomicU128;
    use crate::sync::atomic::Ordering::*;
    use crate::sys::time;
    use crate::time::Duration;

    const ZERO: time::Instant = time::Instant::zero();
    static MONO: AtomicU128 = AtomicU128::new(0);

    #[inline]
    pub(super) fn monotonize(raw: time::Instant) -> time::Instant {
        let delta = raw.checked_sub_instant(&ZERO).unwrap();
        // Split into seconds and nanos since Duration doesn't have a
        // constructor that takes a u128
        let secs = delta.as_secs() as u128;
        let nanos = delta.subsec_nanos() as u128;
        let timestamp: u128 = secs << 64 | nanos;
        let timestamp = MONO.fetch_max(timestamp, Relaxed).max(timestamp);
        let secs = (timestamp >> 64) as u64;
        let nanos = timestamp as u32;
        ZERO.checked_add_duration(&Duration::new(secs, nanos)).unwrap()
    }
}

#[cfg(not(any(target_has_atomic = "64", target_has_atomic = "128")))]
pub mod inner {
    use crate::cmp;
    use crate::sys::time;
    use crate::sys_common::mutex::StaticMutex;

    #[inline]
    pub(super) fn monotonize(os_now: time::Instant) -> time::Instant {
        static LOCK: StaticMutex = StaticMutex::new();
        static mut LAST_NOW: time::Instant = time::Instant::zero();
        unsafe {
            let _lock = LOCK.lock();
            let now = cmp::max(LAST_NOW, os_now);
            LAST_NOW = now;
            now
        }
    }
}
<commit_msg>Rollup merge of #88651 - AGSaidi:monotonize-inner-64b-aarch64, r=dtolnay<commit_after>use crate::sys::time;

#[inline]
pub(super) fn monotonize(raw: time::Instant) -> time::Instant {
    inner::monotonize(raw)
}

#[cfg(any(all(target_has_atomic = "64", not(target_has_atomic = "128")), target_arch = "aarch64"))]
pub mod inner {
    use crate::sync::atomic::AtomicU64;
    use crate::sync::atomic::Ordering::*;
    use crate::sys::time;
    use crate::time::Duration;

    pub(in crate::time) const ZERO: time::Instant = time::Instant::zero();

    // bits 30 and 31 are never used since the nanoseconds part never exceeds 10^9
    const UNINITIALIZED: u64 = 0b11 << 30;
    static MONO: AtomicU64 = AtomicU64::new(UNINITIALIZED);

    #[inline]
    pub(super) fn monotonize(raw: time::Instant) -> time::Instant {
        monotonize_impl(&MONO, raw)
    }

    #[inline]
    pub(in crate::time) fn monotonize_impl(mono: &AtomicU64, raw: time::Instant) -> time::Instant {
        let delta = raw.checked_sub_instant(&ZERO).unwrap();
        let secs = delta.as_secs();
        // occupies no more than 30 bits (10^9 seconds)
        let nanos = delta.subsec_nanos() as u64;

        // This wraps around every 136 years (2^32 seconds).
        // To detect backsliding we use wrapping arithmetic and declare forward steps smaller
        // than 2^31 seconds as expected and everything else as a backslide which will be
        // monotonized.
        // This could be a problem for programs that call instants at intervals greater
        // than 68 years. Interstellar probes may want to ensure that actually_monotonic() is true.
        let packed = (secs << 32) | nanos;
        let updated = mono.fetch_update(Relaxed, Relaxed, |old| {
            (old == UNINITIALIZED || packed.wrapping_sub(old) < u64::MAX / 2).then_some(packed)
        });
        match updated {
            Ok(_) => raw,
            Err(newer) => {
                // Backslide occurred. We reconstruct monotonized time from the upper 32 bit of the
                // passed in value and the 64bits loaded from the atomic
                let seconds_lower = newer >> 32;
                let mut seconds_upper = secs & 0xffff_ffff_0000_0000;
                if secs & 0xffff_ffff > seconds_lower {
                    // Backslide caused the lower 32bit of the seconds part to wrap.
                    // This must be the case because the seconds part is larger even though
                    // we are in the backslide branch, i.e. the seconds count should be smaller or equal.
                    //
                    // We assume that backslides are smaller than 2^32 seconds
                    // which means we need to add 1 to the upper half to restore it.
                    //
                    // Example:
                    // most recent observed time: 0xA1_0000_0000_0000_0000u128
                    // bits stored in AtomicU64:     0x0000_0000_0000_0000u64
                    // backslide by 1s
                    // caller time is             0xA0_ffff_ffff_0000_0000u128
                    // -> we can fix up the upper half time by adding 1 << 32
                    seconds_upper = seconds_upper.wrapping_add(0x1_0000_0000);
                }
                let secs = seconds_upper | seconds_lower;
                let nanos = newer as u32;
                ZERO.checked_add_duration(&Duration::new(secs, nanos)).unwrap()
            }
        }
    }
}

#[cfg(all(target_has_atomic = "128", not(target_arch = "aarch64")))]
pub mod inner {
    use crate::sync::atomic::AtomicU128;
    use crate::sync::atomic::Ordering::*;
    use crate::sys::time;
    use crate::time::Duration;

    const ZERO: time::Instant = time::Instant::zero();
    static MONO: AtomicU128 = AtomicU128::new(0);

    #[inline]
    pub(super) fn monotonize(raw: time::Instant) -> time::Instant {
        let delta = raw.checked_sub_instant(&ZERO).unwrap();
        // Split into seconds and nanos since Duration doesn't have a
        // constructor that takes a u128
        let secs = delta.as_secs() as u128;
        let nanos = delta.subsec_nanos() as u128;
        let timestamp: u128 = secs << 64 | nanos;
        let timestamp = MONO.fetch_max(timestamp, Relaxed).max(timestamp);
        let secs = (timestamp >> 64) as u64;
        let nanos = timestamp as u32;
        ZERO.checked_add_duration(&Duration::new(secs, nanos)).unwrap()
    }
}

#[cfg(not(any(target_has_atomic = "64", target_has_atomic = "128")))]
pub mod inner {
    use crate::cmp;
    use crate::sys::time;
    use crate::sys_common::mutex::StaticMutex;

    #[inline]
    pub(super) fn monotonize(os_now: time::Instant) -> time::Instant {
        static LOCK: StaticMutex = StaticMutex::new();
        static mut LAST_NOW: time::Instant = time::Instant::zero();
        unsafe {
            let _lock = LOCK.lock();
            let now = cmp::max(LAST_NOW, os_now);
            LAST_NOW = now;
            now
        }
    }
}
<|endoftext|>


<commit_before>// Copyright 2018 Google Inc.
//
// 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
//
//     https://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.

use errors::Error;

#[derive(Clone)]
pub(crate) struct ExternalCrate {
    // The name, as it appears in the crate registry. This may be different than the key against
    // which this ExternalCrate is stored. If this name is "foo-bar", the key would be normalized as
    // "foo_bar".
    pub(crate) name: String,
    // Of the form "name = ..."
    pub(crate) config: String,
}

impl ExternalCrate {
    pub(crate) fn new(name: String, config: String) -> Result<ExternalCrate, Error> {
        Ok(ExternalCrate { name, config })
    }
}

#[cfg(test)]
mod tests {
    use super::ExternalCrate;
    use std::env;

    #[test]
    #[ignore]
    fn make_paths_absolute() {
        println!("{:?}", env::current_dir());
        let krate = ExternalCrate::new("foo".to_owned(), "{ path = \"my_crates/foo\" }".to_owned())
            .unwrap();
        assert_eq!(krate.name, "foo");
        assert_eq!(
            krate.config,
            format!(
                "{{ path = \"{}/my_crates/foo\" }}",
                env::current_dir().unwrap().to_string_lossy()
            )
        );
    }
}
<commit_msg>Convert relative paths to absolute paths. Fixes #14<commit_after>// Copyright 2018 Google Inc.
//
// 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
//
//     https://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.

use errors::Error;
use regex::Regex;
use std::path::Path;

#[derive(Clone)]
pub(crate) struct ExternalCrate {
    // The name, as it appears in the crate registry. This may be different than the key against
    // which this ExternalCrate is stored. If this name is "foo-bar", the key would be normalized as
    // "foo_bar".
    pub(crate) name: String,
    // Of the form "name = ..."
    pub(crate) config: String,
}

fn make_paths_absolute(config: String) -> Result<String, Error> {
    // Perhaps not the nicest way to do this. Using a toml parser would possibly
    // be nicer, but when I checked the toml parser used custom derive and if we
    // use any crate that uses custom derive, we end up with a binary that can't
    // be run... at least on older compilers. This was just recently fixed, but
    // I'm not yet ready to drop support for older versions of rustc.
    lazy_static! {
        static ref PATH_RE: Regex = Regex::new("^(.*)path *= *\"([^\"]+)\"(.*)$").unwrap();
    }
    if let Some(captures) = PATH_RE.captures(&config) {
        let path = Path::new(&captures[2]);
        if !path.is_absolute() {
            match path.canonicalize() {
                Ok(path) => {
                    return Ok(captures[1].to_owned()
                        + "path = \""
                        + &path.to_string_lossy()
                        + "\""
                        + &captures[3]);
                }
                Err(err) => {
                    bail!("{}: {:?}", err, path);
                }
            }
        }
    }
    Ok(config)
}

impl ExternalCrate {
    pub(crate) fn new(name: String, config: String) -> Result<ExternalCrate, Error> {
        let config = make_paths_absolute(config)?;
        Ok(ExternalCrate { name, config })
    }
}

#[cfg(test)]
mod tests {
    use super::ExternalCrate;
    use std::path::Path;

    #[test]
    fn make_paths_absolute() {
        let krate =
            ExternalCrate::new("foo".to_owned(), "{ path = \"src/testdata\" }".to_owned()).unwrap();
        assert_eq!(krate.name, "foo");
        assert_eq!(
            krate.config,
            format!(
                "{{ path = \"{}\" }}",
                Path::new("src/testdata")
                    .canonicalize()
                    .unwrap()
                    .to_string_lossy()
            )
        );
    }
}
<|endoftext|>