<commit_before>use alloc::boxed::Box;

use core::cmp;

use common::event::{KeyEvent, MouseEvent};

use drivers::io::{Io, Pio, ReadOnly, WriteOnly};

use graphics::display::VBEMODEINFO;

use fs::KScheme;

use drivers::kb_layouts::layouts;

pub struct Ps2Keyboard<'a> {
    bus: &'a mut Ps2
}

impl<'a> Ps2Keyboard<'a> {
    //TODO: Use result
    fn cmd(&mut self, command: u8) -> u8 {
        self.bus.wait_write();
        self.bus.data.write(command);
        self.bus.wait_read();
        self.bus.data.read()
    }
}

pub struct Ps2Mouse<'a> {
    bus: &'a mut Ps2
}

impl<'a> Ps2Mouse<'a> {
    //TODO: Use result
    fn cmd(&mut self, command: u8) -> u8 {
        self.bus.write(0xD4, command);
        self.bus.wait_read();
        self.bus.data.read()
    }
}

/// PS2
pub struct Ps2 {
    /// The data register
    data: Pio<u8>,
    /// The status register
    sts: ReadOnly<u8, Pio<u8>>,
    /// The command register
    cmd: WriteOnly<u8, Pio<u8>>,
    /// Left shift?
    lshift: bool,
    /// Right shift?
    rshift: bool,
    /// Caps lock?
    caps_lock: bool,
    /// Caps lock toggle
    caps_lock_toggle: bool,
    /// AltGr?
    altgr: bool,
    /// The mouse packet
    mouse_packet: [u8; 4],
    /// Mouse packet index
    mouse_i: usize,
    /// Mouse point x
    mouse_x: i32,
    /// Mouse point y
    mouse_y: i32,
    /// Layout for keyboard
    /// Default: English
    layout: layouts::Layout,
}

impl Ps2 {
    /// Create new PS2 data
    pub fn new() -> Box<Self> {
        let mut module = box Ps2 {
            data: Pio::new(0x60),
            sts: ReadOnly::new(Pio::new(0x64)),
            cmd: WriteOnly::new(Pio::new(0x64)),
            lshift: false,
            rshift: false,
            caps_lock: false,
            caps_lock_toggle: false,
            altgr: false,
            mouse_packet: [0; 4],
            mouse_i: 0,
            mouse_x: 0,
            mouse_y: 0,
            layout: layouts::Layout::English,
        };

        module.init();

        module
    }

    fn wait_read(&self) {
        while ! self.sts.readf(1) {}
    }

    fn wait_write(&self) {
        while self.sts.readf(2) {}
    }

    fn cmd(&mut self, command: u8) {
        self.wait_write();
        self.cmd.write(command);
    }

    fn read(&mut self, command: u8) -> u8 {
        self.cmd(command);
        self.wait_read();
        self.data.read()
    }

    fn write(&mut self, command: u8, data: u8) {
        self.cmd(command);
        self.wait_write();
        self.data.write(data);
    }

    fn keyboard<'a>(&'a mut self) -> Ps2Keyboard<'a> {
        Ps2Keyboard {
            bus: self
        }
    }

    fn mouse<'a>(&'a mut self) -> Ps2Mouse<'a> {
        Ps2Mouse {
            bus: self
        }
    }

    fn init(&mut self) {
        while self.sts.readf(1) {
            self.data.read();
        }

        debugln!(" + PS/2");

        // No interrupts, system flag set, clocks enabled, translation enabled
        self.write(0x60, 0b01000100);

        while self.sts.readf(1) {
            debugln!("Extra {}: {:X}", line!(), self.data.read());
        }

        // Enable First Port
        debugln!("   + Keyboard");
        self.cmd(0xAE);

        while self.sts.readf(1) {
            debugln!("Extra {}: {:X}", line!(), self.data.read());
        }

        {
            // Reset
            debug!("     - Reset {:X}", self.keyboard().cmd(0xFF));
            self.wait_read();
            debugln!(", {:X}", self.data.read());

            while self.sts.readf(1) {
                debugln!("Extra {}: {:X}", line!(), self.data.read());
            }

            // Set defaults
            debugln!("     - Set defaults {:X}", self.keyboard().cmd(0xF6));

            while self.sts.readf(1) {
                debugln!("Extra {}: {:X}", line!(), self.data.read());
            }

            // Enable Streaming
            debugln!("     - Enable streaming {:X}", self.keyboard().cmd(0xF4));

            while self.sts.readf(1) {
                debugln!("Extra {}: {:X}", line!(), self.data.read());
            }
        }

        // Enable Second Port
        debugln!("   + PS/2 Mouse");
        self.cmd(0xA8);

        while self.sts.readf(1) {
            debugln!("Extra {}: {:X}", line!(), self.data.read());
        }

        {
            // Reset
            debug!("     - Reset {:X}", self.keyboard().cmd(0xFF));
            self.wait_read();
            debugln!(", {:X}", self.data.read());

            while self.sts.readf(1) {
                debugln!("Extra {}: {:X}", line!(), self.data.read());
            }

            // Set defaults
            debugln!("     - Set defaults {:X}", self.mouse().cmd(0xF6));

            while self.sts.readf(1) {
                debugln!("Extra {}: {:X}", line!(), self.data.read());
            }

            // Enable Streaming
            debugln!("     - Enable streaming {:X}", self.mouse().cmd(0xF4));

            while self.sts.readf(1) {
                debugln!("Extra {}: {:X}", line!(), self.data.read());
            }
        }

        // Key and mouse interrupts, system flag set, clocks enabled, translation enabled
        self.write(0x60, 0b01000111);

        while self.sts.readf(1) {
            debugln!("Extra {}: {:X}", line!(), self.data.read());
        }
    }

    /// Keyboard interrupt
    pub fn keyboard_interrupt(&mut self, mut scancode: u8) -> Option<KeyEvent> {
        if scancode == 0 {
            return None;
        } else if scancode == 0x2A {
            self.lshift = true;
        } else if scancode == 0xAA {
            self.lshift = false;
        } else if scancode == 0x36 {
            self.rshift = true;
        } else if scancode == 0xB6 {
            self.rshift = false;
        } else if scancode == 0x3A {
            if !self.caps_lock {
                self.caps_lock = true;
                self.caps_lock_toggle = true;
            } else {
                self.caps_lock_toggle = false;
            }
        } else if scancode == 0xBA {
            if self.caps_lock && !self.caps_lock_toggle {
                self.caps_lock = false;
            }
        } else if scancode == 0xE0 {
            let scancode_byte_2 = self.data.read();
            if scancode_byte_2 == 0x38 {
                self.altgr = true;
            } else if scancode_byte_2 == 0xB8 {
                self.altgr = false;
            } else {
                scancode = scancode_byte_2;
            }
        }

        let shift = self.caps_lock != (self.lshift || self.rshift);

        return Some(KeyEvent {
            character: layouts::char_for_scancode(scancode & 0x7F, shift, self.altgr, &self.layout),
            scancode: scancode & 0x7F,
            pressed: scancode < 0x80,
        });
    }

    /// Mouse interrupt
    pub fn mouse_interrupt(&mut self, byte: u8) -> Option<MouseEvent> {
        if self.mouse_i == 0 {
            if byte & 0x8 == 0x8 {
                self.mouse_packet[0] = byte;
                self.mouse_i += 1;
            }
        } else if self.mouse_i == 1 {
            self.mouse_packet[1] = byte;

            self.mouse_i += 1;
        } else {
            self.mouse_packet[2] = byte;

            let left_button = (self.mouse_packet[0] & 1) == 1;
            let right_button = (self.mouse_packet[0] & 2) == 2;
            let middle_button = (self.mouse_packet[0] & 4) == 4;

            let x;
            if (self.mouse_packet[0] & 0x40) != 0x40 && self.mouse_packet[1] != 0 {
                x = (self.mouse_packet[1] as isize -
                     (((self.mouse_packet[0] as isize) << 4) & 0x100)) as i32;
            } else {
                x = 0;
            }

            let y;
            if (self.mouse_packet[0] & 0x80) != 0x80 && self.mouse_packet[2] != 0 {
                y = ((((self.mouse_packet[0] as isize) << 3) & 0x100) -
                     self.mouse_packet[2] as isize) as i32;
            } else {
                y = 0;
            }

            if let Some(mode_info) = unsafe { VBEMODEINFO } {
                self.mouse_x = cmp::max(0, cmp::min(mode_info.xresolution as i32, self.mouse_x + x));
                self.mouse_y = cmp::max(0, cmp::min(mode_info.yresolution as i32, self.mouse_y + y));
            }

            self.mouse_i = 0;

            return Some(MouseEvent {
                x: self.mouse_x,
                y: self.mouse_y,
                left_button: left_button,
                right_button: right_button,
                middle_button: middle_button,
            });
        }

        return None;
    }

    /// Function to change the layout of the keyboard
    pub fn change_layout(&mut self, layout: usize) {
        self.layout = match layout {
            0 => layouts::Layout::English,
            1 => layouts::Layout::French,
            2 => layouts::Layout::German,
            _ => layouts::Layout::English,
        }
    }
}

impl KScheme for Ps2 {
    fn on_irq(&mut self, irq: u8) {
        if irq == 0xC {
            let data = self.data.read();
            if let Some(mouse_event) = self.mouse_interrupt(data) {
                if ::env().console.lock().draw {
                    //Ignore mouse event
                } else {
                    ::env().events.send(mouse_event.to_event());
                }
            }
        } else if irq == 1 {
            let data = self.data.read();
            if let Some(key_event) = self.keyboard_interrupt(data) {
                if ::env().console.lock().draw {
                    ::env().console.lock().event(key_event.to_event());
                } else {
                    ::env().events.send(key_event.to_event());
                }
            }
        }
    }
}
<commit_msg>Fix swapping of mouse/keyboard<commit_after>use alloc::boxed::Box;

use core::cmp;

use common::event::{KeyEvent, MouseEvent};

use drivers::io::{Io, Pio, ReadOnly, WriteOnly};

use graphics::display::VBEMODEINFO;

use fs::KScheme;

use drivers::kb_layouts::layouts;

pub struct Ps2Keyboard<'a> {
    bus: &'a mut Ps2
}

impl<'a> Ps2Keyboard<'a> {
    //TODO: Use result
    fn cmd(&mut self, command: u8) -> u8 {
        self.bus.wait_write();
        self.bus.data.write(command);
        self.bus.wait_read();
        self.bus.data.read()
    }
}

pub struct Ps2Mouse<'a> {
    bus: &'a mut Ps2
}

impl<'a> Ps2Mouse<'a> {
    //TODO: Use result
    fn cmd(&mut self, command: u8) -> u8 {
        self.bus.write(0xD4, command);
        self.bus.wait_read();
        self.bus.data.read()
    }
}

/// PS2
pub struct Ps2 {
    /// The data register
    data: Pio<u8>,
    /// The status register
    sts: ReadOnly<u8, Pio<u8>>,
    /// The command register
    cmd: WriteOnly<u8, Pio<u8>>,
    /// Left shift?
    lshift: bool,
    /// Right shift?
    rshift: bool,
    /// Caps lock?
    caps_lock: bool,
    /// Caps lock toggle
    caps_lock_toggle: bool,
    /// AltGr?
    altgr: bool,
    /// The mouse packet
    mouse_packet: [u8; 4],
    /// Mouse packet index
    mouse_i: usize,
    /// Mouse point x
    mouse_x: i32,
    /// Mouse point y
    mouse_y: i32,
    /// Layout for keyboard
    /// Default: English
    layout: layouts::Layout,
}

impl Ps2 {
    /// Create new PS2 data
    pub fn new() -> Box<Self> {
        let mut module = box Ps2 {
            data: Pio::new(0x60),
            sts: ReadOnly::new(Pio::new(0x64)),
            cmd: WriteOnly::new(Pio::new(0x64)),
            lshift: false,
            rshift: false,
            caps_lock: false,
            caps_lock_toggle: false,
            altgr: false,
            mouse_packet: [0; 4],
            mouse_i: 0,
            mouse_x: 0,
            mouse_y: 0,
            layout: layouts::Layout::English,
        };

        module.init();

        module
    }

    fn wait_read(&self) {
        while ! self.sts.readf(1) {}
    }

    fn wait_write(&self) {
        while self.sts.readf(2) {}
    }

    fn cmd(&mut self, command: u8) {
        self.wait_write();
        self.cmd.write(command);
    }

    fn read(&mut self, command: u8) -> u8 {
        self.cmd(command);
        self.wait_read();
        self.data.read()
    }

    fn write(&mut self, command: u8, data: u8) {
        self.cmd(command);
        self.wait_write();
        self.data.write(data);
    }

    fn keyboard<'a>(&'a mut self) -> Ps2Keyboard<'a> {
        Ps2Keyboard {
            bus: self
        }
    }

    fn mouse<'a>(&'a mut self) -> Ps2Mouse<'a> {
        Ps2Mouse {
            bus: self
        }
    }

    fn init(&mut self) {
        while self.sts.readf(1) {
            self.data.read();
        }

        debugln!(" + PS/2");

        // No interrupts, system flag set, clocks enabled, translation enabled
        self.write(0x60, 0b01000100);

        while self.sts.readf(1) {
            debugln!("Extra {}: {:X}", line!(), self.data.read());
        }

        // Enable First Port
        debugln!("   + Keyboard");
        self.cmd(0xAE);

        while self.sts.readf(1) {
            debugln!("Extra {}: {:X}", line!(), self.data.read());
        }

        {
            // Reset
            debug!("     - Reset {:X}", self.keyboard().cmd(0xFF));
            self.wait_read();
            debugln!(", {:X}", self.data.read());

            while self.sts.readf(1) {
                debugln!("Extra {}: {:X}", line!(), self.data.read());
            }

            // Set defaults
            debugln!("     - Set defaults {:X}", self.keyboard().cmd(0xF6));

            while self.sts.readf(1) {
                debugln!("Extra {}: {:X}", line!(), self.data.read());
            }

            // Enable Streaming
            debugln!("     - Enable streaming {:X}", self.keyboard().cmd(0xF4));

            while self.sts.readf(1) {
                debugln!("Extra {}: {:X}", line!(), self.data.read());
            }
        }

        // Enable Second Port
        debugln!("   + PS/2 Mouse");
        self.cmd(0xA8);

        while self.sts.readf(1) {
            debugln!("Extra {}: {:X}", line!(), self.data.read());
        }

        {
            // Reset
            debug!("     - Reset {:X}", self.keyboard().cmd(0xFF));
            self.wait_read();
            debugln!(", {:X}", self.data.read());

            while self.sts.readf(1) {
                debugln!("Extra {}: {:X}", line!(), self.data.read());
            }

            // Set defaults
            debugln!("     - Set defaults {:X}", self.mouse().cmd(0xF6));

            while self.sts.readf(1) {
                debugln!("Extra {}: {:X}", line!(), self.data.read());
            }

            // Enable Streaming
            debugln!("     - Enable streaming {:X}", self.mouse().cmd(0xF4));

            while self.sts.readf(1) {
                debugln!("Extra {}: {:X}", line!(), self.data.read());
            }
        }

        // Key and mouse interrupts, system flag set, clocks enabled, translation enabled
        self.write(0x60, 0b01000111);

        while self.sts.readf(1) {
            debugln!("Extra {}: {:X}", line!(), self.data.read());
        }
    }

    /// Keyboard interrupt
    pub fn keyboard_interrupt(&mut self, mut scancode: u8) -> Option<KeyEvent> {
        if scancode == 0 {
            return None;
        } else if scancode == 0x2A {
            self.lshift = true;
        } else if scancode == 0xAA {
            self.lshift = false;
        } else if scancode == 0x36 {
            self.rshift = true;
        } else if scancode == 0xB6 {
            self.rshift = false;
        } else if scancode == 0x3A {
            if !self.caps_lock {
                self.caps_lock = true;
                self.caps_lock_toggle = true;
            } else {
                self.caps_lock_toggle = false;
            }
        } else if scancode == 0xBA {
            if self.caps_lock && !self.caps_lock_toggle {
                self.caps_lock = false;
            }
        } else if scancode == 0xE0 {
            let scancode_byte_2 = self.data.read();
            if scancode_byte_2 == 0x38 {
                self.altgr = true;
            } else if scancode_byte_2 == 0xB8 {
                self.altgr = false;
            } else {
                scancode = scancode_byte_2;
            }
        }

        let shift = self.caps_lock != (self.lshift || self.rshift);

        return Some(KeyEvent {
            character: layouts::char_for_scancode(scancode & 0x7F, shift, self.altgr, &self.layout),
            scancode: scancode & 0x7F,
            pressed: scancode < 0x80,
        });
    }

    /// Mouse interrupt
    pub fn mouse_interrupt(&mut self, byte: u8) -> Option<MouseEvent> {
        if self.mouse_i == 0 {
            if byte & 0x8 == 0x8 {
                self.mouse_packet[0] = byte;
                self.mouse_i += 1;
            }
        } else if self.mouse_i == 1 {
            self.mouse_packet[1] = byte;

            self.mouse_i += 1;
        } else {
            self.mouse_packet[2] = byte;

            let left_button = (self.mouse_packet[0] & 1) == 1;
            let right_button = (self.mouse_packet[0] & 2) == 2;
            let middle_button = (self.mouse_packet[0] & 4) == 4;

            let x;
            if (self.mouse_packet[0] & 0x40) != 0x40 && self.mouse_packet[1] != 0 {
                x = (self.mouse_packet[1] as isize -
                     (((self.mouse_packet[0] as isize) << 4) & 0x100)) as i32;
            } else {
                x = 0;
            }

            let y;
            if (self.mouse_packet[0] & 0x80) != 0x80 && self.mouse_packet[2] != 0 {
                y = ((((self.mouse_packet[0] as isize) << 3) & 0x100) -
                     self.mouse_packet[2] as isize) as i32;
            } else {
                y = 0;
            }

            if let Some(mode_info) = unsafe { VBEMODEINFO } {
                self.mouse_x = cmp::max(0, cmp::min(mode_info.xresolution as i32, self.mouse_x + x));
                self.mouse_y = cmp::max(0, cmp::min(mode_info.yresolution as i32, self.mouse_y + y));
            }

            self.mouse_i = 0;

            return Some(MouseEvent {
                x: self.mouse_x,
                y: self.mouse_y,
                left_button: left_button,
                right_button: right_button,
                middle_button: middle_button,
            });
        }

        return None;
    }

    /// Function to change the layout of the keyboard
    pub fn change_layout(&mut self, layout: usize) {
        self.layout = match layout {
            0 => layouts::Layout::English,
            1 => layouts::Layout::French,
            2 => layouts::Layout::German,
            _ => layouts::Layout::English,
        }
    }
}

impl KScheme for Ps2 {
    fn on_irq(&mut self, irq: u8) {
        if irq == 0xC || irq == 0x1 {
            loop {
                let status = self.sts.read();
                if status & 0x21 == 0x21 {
                    let data = self.data.read();
                    if let Some(mouse_event) = self.mouse_interrupt(data) {
                        if ::env().console.lock().draw {
                            //Ignore mouse event
                        } else {
                            ::env().events.send(mouse_event.to_event());
                        }
                    }
                } else if status & 0x21 == 0x01 {
                    let data = self.data.read();
                    if let Some(key_event) = self.keyboard_interrupt(data) {
                        if ::env().console.lock().draw {
                            ::env().console.lock().event(key_event.to_event());
                        } else {
                            ::env().events.send(key_event.to_event());
                        }
                    }
                } else {
                    break;
                }
            }
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Rollup merge of #62193 - matthewjasper:dynamic-drop-async, r=Centril<commit_after>// Test that values are not leaked in async functions, even in the cases where:
// * Dropping one of the values panics while running the future.
// * The future is dropped at one of its suspend points.
// * Dropping one of the values panics while dropping the future.

// run-pass
// edition:2018
// ignore-wasm32-bare compiled with panic=abort by default

#![allow(unused_assignments)]
#![allow(unused_variables)]
#![feature(slice_patterns)]
#![feature(async_await)]

use std::{
    cell::{Cell, RefCell},
    future::Future,
    marker::Unpin,
    panic,
    pin::Pin,
    ptr,
    rc::Rc,
    task::{Context, Poll, RawWaker, RawWakerVTable, Waker},
    usize,
};

struct InjectedFailure;

struct Defer<T> {
    ready: bool,
    value: Option<T>,
}

impl<T: Unpin> Future for Defer<T> {
    type Output = T;
    fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
        if self.ready {
            Poll::Ready(self.value.take().unwrap())
        } else {
            self.ready = true;
            Poll::Pending
        }
    }
}

/// Allocator tracks the creation and destruction of `Ptr`s.
/// The `failing_op`-th operation will panic.
struct Allocator {
    data: RefCell<Vec<bool>>,
    failing_op: usize,
    cur_ops: Cell<usize>,
}

impl panic::UnwindSafe for Allocator {}
impl panic::RefUnwindSafe for Allocator {}

impl Drop for Allocator {
    fn drop(&mut self) {
        let data = self.data.borrow();
        if data.iter().any(|d| *d) {
            panic!("missing free: {:?}", data);
        }
    }
}

impl Allocator {
    fn new(failing_op: usize) -> Self {
        Allocator { failing_op, cur_ops: Cell::new(0), data: RefCell::new(vec![]) }
    }
    fn alloc(&self) -> impl Future<Output = Ptr<'_>> + '_ {
        self.fallible_operation();

        let mut data = self.data.borrow_mut();

        let addr = data.len();
        data.push(true);
        Defer { ready: false, value: Some(Ptr(addr, self)) }
    }
    fn fallible_operation(&self) {
        self.cur_ops.set(self.cur_ops.get() + 1);

        if self.cur_ops.get() == self.failing_op {
            panic!(InjectedFailure);
        }
    }
}

// Type that tracks whether it was dropped and can panic when it's created or
// destroyed.
struct Ptr<'a>(usize, &'a Allocator);
impl<'a> Drop for Ptr<'a> {
    fn drop(&mut self) {
        match self.1.data.borrow_mut()[self.0] {
            false => panic!("double free at index {:?}", self.0),
            ref mut d => *d = false,
        }

        self.1.fallible_operation();
    }
}

async fn dynamic_init(a: Rc<Allocator>, c: bool) {
    let _x;
    if c {
        _x = Some(a.alloc().await);
    }
}

async fn dynamic_drop(a: Rc<Allocator>, c: bool) {
    let x = a.alloc().await;
    if c {
        Some(x)
    } else {
        None
    };
}

struct TwoPtrs<'a>(Ptr<'a>, Ptr<'a>);
async fn struct_dynamic_drop(a: Rc<Allocator>, c0: bool, c1: bool, c: bool) {
    for i in 0..2 {
        let x;
        let y;
        if (c0 && i == 0) || (c1 && i == 1) {
            x = (a.alloc().await, a.alloc().await, a.alloc().await);
            y = TwoPtrs(a.alloc().await, a.alloc().await);
            if c {
                drop(x.1);
                a.alloc().await;
                drop(y.0);
                a.alloc().await;
            }
        }
    }
}

async fn field_assignment(a: Rc<Allocator>, c0: bool) {
    let mut x = (TwoPtrs(a.alloc().await, a.alloc().await), a.alloc().await);

    x.1 = a.alloc().await;
    x.1 = a.alloc().await;

    let f = (x.0).0;
    a.alloc().await;
    if c0 {
        (x.0).0 = f;
    }
    a.alloc().await;
}

async fn assignment(a: Rc<Allocator>, c0: bool, c1: bool) {
    let mut _v = a.alloc().await;
    let mut _w = a.alloc().await;
    if c0 {
        drop(_v);
    }
    _v = _w;
    if c1 {
        _w = a.alloc().await;
    }
}

async fn array_simple(a: Rc<Allocator>) {
    let _x = [a.alloc().await, a.alloc().await, a.alloc().await, a.alloc().await];
}

async fn vec_simple(a: Rc<Allocator>) {
    let _x = vec![a.alloc().await, a.alloc().await, a.alloc().await, a.alloc().await];
}

async fn mixed_drop_and_nondrop(a: Rc<Allocator>) {
    // check that destructor panics handle drop
    // and non-drop blocks in the same scope correctly.
    //
    // Surprisingly enough, this used to not work.
    let (x, y, z);
    x = a.alloc().await;
    y = 5;
    z = a.alloc().await;
}

#[allow(unreachable_code)]
async fn vec_unreachable(a: Rc<Allocator>) {
    let _x = vec![a.alloc().await, a.alloc().await, a.alloc().await, return];
}

async fn slice_pattern_one_of(a: Rc<Allocator>, i: usize) {
    let array = [a.alloc().await, a.alloc().await, a.alloc().await, a.alloc().await];
    let _x = match i {
        0 => {
            let [a, ..] = array;
            a
        }
        1 => {
            let [_, a, ..] = array;
            a
        }
        2 => {
            let [_, _, a, _] = array;
            a
        }
        3 => {
            let [_, _, _, a] = array;
            a
        }
        _ => panic!("unmatched"),
    };
    a.alloc().await;
}

async fn subslice_pattern_from_end_with_drop(a: Rc<Allocator>, arg: bool, arg2: bool) {
    let arr = [a.alloc().await, a.alloc().await, a.alloc().await, a.alloc().await, a.alloc().await];
    if arg2 {
        drop(arr);
        return;
    }

    if arg {
        let [.., _x, _] = arr;
    } else {
        let [_, _y..] = arr;
    }
    a.alloc().await;
}

async fn subslice_pattern_reassign(a: Rc<Allocator>) {
    let mut ar = [a.alloc().await, a.alloc().await, a.alloc().await];
    let [_, _, _x] = ar;
    ar = [a.alloc().await, a.alloc().await, a.alloc().await];
    let [_, _y..] = ar;
    a.alloc().await;
}

fn run_test<F, G>(cx: &mut Context<'_>, ref f: F)
where
    F: Fn(Rc<Allocator>) -> G,
    G: Future<Output = ()>,
{
    for polls in 0.. {
        // Run without any panics to find which operations happen after the
        // penultimate `poll`.
        let first_alloc = Rc::new(Allocator::new(usize::MAX));
        let mut fut = Box::pin(f(first_alloc.clone()));
        let mut ops_before_last_poll = 0;
        let mut completed = false;
        for _ in 0..polls {
            ops_before_last_poll = first_alloc.cur_ops.get();
            if let Poll::Ready(()) = fut.as_mut().poll(cx) {
                completed = true;
            }
        }
        drop(fut);

        // Start at `ops_before_last_poll` so that we will always be able to
        // `poll` the expected number of times.
        for failing_op in ops_before_last_poll..first_alloc.cur_ops.get() {
            let alloc = Rc::new(Allocator::new(failing_op + 1));
            let f = &f;
            let cx = &mut *cx;
            let result = panic::catch_unwind(panic::AssertUnwindSafe(move || {
                let mut fut = Box::pin(f(alloc));
                for _ in 0..polls {
                    let _ = fut.as_mut().poll(cx);
                }
                drop(fut);
            }));
            match result {
                Ok(..) => panic!("test executed more ops on first call"),
                Err(e) => {
                    if e.downcast_ref::<InjectedFailure>().is_none() {
                        panic::resume_unwind(e);
                    }
                }
            }
        }

        if completed {
            break;
        }
    }
}

fn clone_waker(data: *const ()) -> RawWaker {
    RawWaker::new(data, &RawWakerVTable::new(clone_waker, drop, drop, drop))
}

fn main() {
    let waker = unsafe { Waker::from_raw(clone_waker(ptr::null())) };
    let context = &mut Context::from_waker(&waker);

    run_test(context, |a| dynamic_init(a, false));
    run_test(context, |a| dynamic_init(a, true));
    run_test(context, |a| dynamic_drop(a, false));
    run_test(context, |a| dynamic_drop(a, true));

    run_test(context, |a| assignment(a, false, false));
    run_test(context, |a| assignment(a, false, true));
    run_test(context, |a| assignment(a, true, false));
    run_test(context, |a| assignment(a, true, true));

    run_test(context, |a| array_simple(a));
    run_test(context, |a| vec_simple(a));
    run_test(context, |a| vec_unreachable(a));

    run_test(context, |a| struct_dynamic_drop(a, false, false, false));
    run_test(context, |a| struct_dynamic_drop(a, false, false, true));
    run_test(context, |a| struct_dynamic_drop(a, false, true, false));
    run_test(context, |a| struct_dynamic_drop(a, false, true, true));
    run_test(context, |a| struct_dynamic_drop(a, true, false, false));
    run_test(context, |a| struct_dynamic_drop(a, true, false, true));
    run_test(context, |a| struct_dynamic_drop(a, true, true, false));
    run_test(context, |a| struct_dynamic_drop(a, true, true, true));

    run_test(context, |a| field_assignment(a, false));
    run_test(context, |a| field_assignment(a, true));

    run_test(context, |a| mixed_drop_and_nondrop(a));

    run_test(context, |a| slice_pattern_one_of(a, 0));
    run_test(context, |a| slice_pattern_one_of(a, 1));
    run_test(context, |a| slice_pattern_one_of(a, 2));
    run_test(context, |a| slice_pattern_one_of(a, 3));

    run_test(context, |a| subslice_pattern_from_end_with_drop(a, true, true));
    run_test(context, |a| subslice_pattern_from_end_with_drop(a, true, false));
    run_test(context, |a| subslice_pattern_from_end_with_drop(a, false, true));
    run_test(context, |a| subslice_pattern_from_end_with_drop(a, false, false));
    run_test(context, |a| subslice_pattern_reassign(a));
}
<|endoftext|>


<commit_before><commit_msg>sensors: mpl115a2: fix unit tests to use two's complement<commit_after><|endoftext|>


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

// Regression test for #3512 - conflicting trait impls in different crates should give a
// 'conflicting implementations' error message.

// aux-build:trait_impl_conflict.rs
extern crate trait_impl_conflict;
use trait_impl_conflict::Foo;

impl<A> Foo for A {
    //~^ ERROR type parameter `A` must be used as the type parameter for some local type
    //~^^ ERROR E0119
}

fn main() {
}
<commit_msg>Adjust coherence test to reflect that only the orphan rule prevents you from adding *generalizing* impls<commit_after>// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

// The error here is strictly due to orphan rules; the impl here
// generalizes the one upstream

// aux-build:trait_impl_conflict.rs
extern crate trait_impl_conflict;
use trait_impl_conflict::Foo;

impl<A> Foo for A {
    //~^ ERROR type parameter `A` must be used as the type parameter for some local type
}

fn main() {
}
<|endoftext|>


<commit_before><commit_msg>test(server): add benchmark of hyper server vs raw tcp<commit_after>#![feature(test)]
#![deny(warnings)]

extern crate futures;
extern crate hyper;
extern crate pretty_env_logger;
extern crate test;

use std::io::{Read, Write};
use std::net::{TcpListener, TcpStream, SocketAddr};
use std::sync::mpsc;

use futures::Future;
use futures::sync::oneshot;

use hyper::header::{ContentLength, ContentType};
use hyper::server::{self, Service};

#[bench]
fn bench_server_tcp_throughput(b: &mut test::Bencher) {
    let (_until_tx, until_rx) = oneshot::channel();
    let addr = spawn_hello(until_rx);

    let mut tcp = TcpStream::connect(addr).unwrap();
    let mut buf = [0u8; 4096];

    b.bytes = 130 + 35;
    b.iter(|| {
        tcp.write_all(b"GET / HTTP/1.1\r\nHost: localhost\r\n\r\n").unwrap();
        let n = tcp.read(&mut buf).unwrap();
        assert_eq!(n, 130);
    })
}

#[bench]
fn bench_raw_tcp_throughput(b: &mut test::Bencher) {
    let (tx, rx) = mpsc::channel();
    let listener = TcpListener::bind("127.0.0.1:0").unwrap();
    let addr = listener.local_addr().unwrap();
    ::std::thread::spawn(move || {
        let mut sock = listener.accept().unwrap().0;

        let mut buf = [0u8; 4096];
        while rx.try_recv().is_err() {
            sock.read(&mut buf).unwrap();
            sock.write_all(b"\
                HTTP/1.1 200 OK\r\n\
                Content-Length: 13\r\n\
                Content-Type: text/plain; charset=utf-8\r\n\
                Date: Fri, 12 May 2017 18:21:45 GMT\r\n\
                \r\n\
                Hello, World!\
            ").unwrap();
        }
    });

    let mut tcp = TcpStream::connect(addr).unwrap();
    let mut buf = [0u8; 4096];

    b.bytes = 130 + 35;
    b.iter(|| {
        tcp.write_all(b"GET / HTTP/1.1\r\nHost: localhost\r\n\r\n").unwrap();
        let n = tcp.read(&mut buf).unwrap();
        assert_eq!(n, 130);
    });
    tx.send(()).unwrap();
}

struct Hello;

impl Service for Hello {
    type Request = server::Request;
    type Response = server::Response;
    type Error = hyper::Error;
    type Future = ::futures::Finished<Self::Response, hyper::Error>;
    fn call(&self, _req: Self::Request) -> Self::Future {
        ::futures::finished(
            server::Response::new()
                .with_header(ContentLength("Hello, World!".len() as u64))
                .with_header(ContentType::plaintext())
                .with_body("Hello, World!")
        )
    }
}

fn spawn_hello(until: oneshot::Receiver<()>) -> SocketAddr {
    let (addr_tx, addr_rx) = mpsc::channel();
    ::std::thread::spawn(move || {
        let addr = "127.0.0.1:0".parse().unwrap();
        let srv = hyper::server::Http::new().bind(&addr, || Ok(Hello)).unwrap();
        let addr = srv.local_addr().unwrap();
        addr_tx.send(addr).unwrap();
        srv.run_until(until.map_err(|_| ())).unwrap();
    });

    addr_rx.recv().unwrap()
}
<|endoftext|>


<commit_before><commit_msg>Add regression test for #70673<commit_after>// Regression test for https://github.com/rust-lang/rust/issues/70673.

// run-pass

#![feature(thread_local)]

#[thread_local]
static A: &u8 = &42;

fn main() {
    dbg!(*A);
}
<|endoftext|>


<commit_before>// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

use std::fs::File;
use std::io::Read;
use std::path::PathBuf;

use libmount;
use nix::mount::{MntFlags, umount2};

use devicemapper::{DevId, DmOptions};

use super::super::dm::{get_dm, get_dm_init};

#[allow(renamed_and_removed_lints)]
mod cleanup_errors {
    use libmount;
    use nix;
    use std;

    error_chain!{
        foreign_links {
            Ioe(std::io::Error);
            Mnt(libmount::mountinfo::ParseError);
            Nix(nix::Error);
        }
    }
}

use self::cleanup_errors::{Error, Result};

/// Attempt to remove all device mapper devices which match the stratis naming convention.
/// FIXME: Current implementation complicated by https://bugzilla.redhat.com/show_bug.cgi?id=1506287
fn dm_stratis_devices_remove() -> Result<()> {
    /// One iteration of removing devicemapper devices
    fn one_iteration() -> Result<(bool, Vec<String>)> {
        let mut progress_made = false;
        let mut remain = Vec::new();

        for n in get_dm()
            .list_devices()
            .map_err(|e| {
                let err_msg = "failed while listing DM devices, giving up";
                Error::with_chain(e, err_msg)
            })?
            .iter()
            .map(|d| &d.0)
            .filter(|n| n.to_string().starts_with("stratis-1"))
        {
            match get_dm().device_remove(&DevId::Name(n), &DmOptions::new()) {
                Ok(_) => progress_made = true,
                Err(_) => remain.push(n.to_string()),
            }
        }
        Ok((progress_made, remain))
    }

    /// Do one iteration of removals until progress stops. Return remaining
    /// dm devices.
    fn do_while_progress() -> Result<Vec<String>> {
        let mut result = one_iteration()?;
        while result.0 {
            result = one_iteration()?;
        }
        Ok(result.1)
    }

    || -> Result<()> {
        get_dm_init().map_err(|err| Error::with_chain(err, "Unable to initialize DM"))?;
        do_while_progress().and_then(|remain| {
            if !remain.is_empty() {
                Err(format!("Some Stratis DM devices remaining: {:?}", remain).into())
            } else {
                Ok(())
            }
        })
    }().map_err(|e| e.chain_err(|| "Failed to ensure removal of all Stratis DM devices"))
}

/// Try and un-mount any filesystems that have the name stratis in the mount point, returning
/// immediately on the first one we are unable to unmount.
fn stratis_filesystems_unmount() -> Result<()> {
    || -> Result<()> {
        let mut mount_data = String::new();
        File::open("/proc/self/mountinfo")?.read_to_string(&mut mount_data)?;
        let parser = libmount::mountinfo::Parser::new(mount_data.as_bytes());

        for mount_point in parser
            .into_iter()
            .filter_map(|x| x.ok())
            .filter_map(|m| m.mount_point.into_owned().into_string().ok())
            .filter(|mp| mp.contains("stratis"))
        {
            umount2(&PathBuf::from(mount_point), MntFlags::MNT_DETACH)?;
        }

        Ok(())
    }().map_err(|e| e.chain_err(|| "Failed to ensure all Stratis filesystems were unmounted"))
}

/// When a unit test panics we can leave the system in an inconsistent state.  This function
/// tries to clean up by un-mounting any mounted file systems which contain the string
/// "stratis_testing" and then it tries to remove any device mapper tables which are also stratis
/// created.
pub fn clean_up() -> Result<()> {
    stratis_filesystems_unmount()?;
    dm_stratis_devices_remove()?;
    Ok(())
}
<commit_msg>Add a call to udev_settle() to sync udev db and DM before we try to cleanup the DM devices when a test is complete.<commit_after>// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

use std::fs::File;
use std::io::Read;
use std::path::PathBuf;

use libmount;
use nix::mount::{MntFlags, umount2};

use devicemapper::{DevId, DmOptions};

use super::super::cmd;
use super::super::dm::{get_dm, get_dm_init};

#[allow(renamed_and_removed_lints)]
mod cleanup_errors {
    use libmount;
    use nix;
    use std;

    error_chain!{
        foreign_links {
            Ioe(std::io::Error);
            Mnt(libmount::mountinfo::ParseError);
            Nix(nix::Error);
        }
    }
}

use self::cleanup_errors::{Error, Result};

/// Attempt to remove all device mapper devices which match the stratis naming convention.
/// FIXME: Current implementation complicated by https://bugzilla.redhat.com/show_bug.cgi?id=1506287
fn dm_stratis_devices_remove() -> Result<()> {
    /// One iteration of removing devicemapper devices
    fn one_iteration() -> Result<(bool, Vec<String>)> {
        let mut progress_made = false;
        let mut remain = Vec::new();

        for n in get_dm()
            .list_devices()
            .map_err(|e| {
                let err_msg = "failed while listing DM devices, giving up";
                Error::with_chain(e, err_msg)
            })?
            .iter()
            .map(|d| &d.0)
            .filter(|n| n.to_string().starts_with("stratis-1"))
        {
            match get_dm().device_remove(&DevId::Name(n), &DmOptions::new()) {
                Ok(_) => progress_made = true,
                Err(_) => remain.push(n.to_string()),
            }
        }
        Ok((progress_made, remain))
    }

    /// Do one iteration of removals until progress stops. Return remaining
    /// dm devices.
    fn do_while_progress() -> Result<Vec<String>> {
        let mut result = one_iteration()?;
        while result.0 {
            result = one_iteration()?;
        }
        Ok(result.1)
    }

    || -> Result<()> {
        cmd::udev_settle().unwrap();
        get_dm_init().map_err(|err| Error::with_chain(err, "Unable to initialize DM"))?;
        do_while_progress().and_then(|remain| {
            if !remain.is_empty() {
                Err(format!("Some Stratis DM devices remaining: {:?}", remain).into())
            } else {
                Ok(())
            }
        })
    }().map_err(|e| e.chain_err(|| "Failed to ensure removal of all Stratis DM devices"))
}

/// Try and un-mount any filesystems that have the name stratis in the mount point, returning
/// immediately on the first one we are unable to unmount.
fn stratis_filesystems_unmount() -> Result<()> {
    || -> Result<()> {
        let mut mount_data = String::new();
        File::open("/proc/self/mountinfo")?.read_to_string(&mut mount_data)?;
        let parser = libmount::mountinfo::Parser::new(mount_data.as_bytes());

        for mount_point in parser
            .into_iter()
            .filter_map(|x| x.ok())
            .filter_map(|m| m.mount_point.into_owned().into_string().ok())
            .filter(|mp| mp.contains("stratis"))
        {
            umount2(&PathBuf::from(mount_point), MntFlags::MNT_DETACH)?;
        }

        Ok(())
    }().map_err(|e| e.chain_err(|| "Failed to ensure all Stratis filesystems were unmounted"))
}

/// When a unit test panics we can leave the system in an inconsistent state.  This function
/// tries to clean up by un-mounting any mounted file systems which contain the string
/// "stratis_testing" and then it tries to remove any device mapper tables which are also stratis
/// created.
pub fn clean_up() -> Result<()> {
    stratis_filesystems_unmount()?;
    dm_stratis_devices_remove()?;
    Ok(())
}
<|endoftext|>


<commit_before><commit_msg>Work on PSR Transfers<commit_after><|endoftext|>


<commit_before><commit_msg>add problem 14 in rust<commit_after>fn collatz(num: u32) -> u32 {
    if num == 1 {
        return num;
    }

    if num % 2 == 0 {
        num / 2
    } else {
        (num * 3) + 1
    }
}

fn main() {
    let mut max_terms: u32 = 0;
    let mut max_terms_number: u32 = 0;

    for i in (2..1_000_000).rev() {
        let mut current_terms: u32 = 0;
        let mut result: u32 = i;
        while result != 1 {
            result = collatz(result);
            current_terms += 1;
            if current_terms > max_terms {
                max_terms = current_terms;
                max_terms_number = i;
            }
        }
        // println!("collatz({}) -> {}", i, current_terms);
    }

    println!("Result: {}", max_terms_number);
}
<|endoftext|>


<commit_before><commit_msg>performing yolo tasks.<commit_after>fn main(){
println("hello");
}
<|endoftext|>


<commit_before><commit_msg>Add test for issue-69840<commit_after>// check-pass

#![feature(impl_trait_in_bindings)]
#![allow(incomplete_features)]

struct A<'a>(&'a ());

trait Trait<T> {}

impl<T> Trait<T> for () {}

pub fn foo<'a>() {
    let _x: impl Trait<A<'a>> = ();
}

fn main() {}
<|endoftext|>


<commit_before><commit_msg>Added workspace support.<commit_after><|endoftext|>


<commit_before><commit_msg>adding explicit lifetime to closure of current braces only<commit_after><|endoftext|>


<commit_before><commit_msg>Add regression test for issue 845<commit_after>use serde::{Deserialize, Deserializer};
use std::convert::TryFrom;
use std::fmt::{self, Display};
use std::marker::PhantomData;
use std::str::FromStr;

pub struct NumberVisitor<T> {
    marker: PhantomData<T>,
}

impl<'de, T> serde::de::Visitor<'de> for NumberVisitor<T>
where
    T: TryFrom<u64> + TryFrom<i64> + FromStr,
    <T as TryFrom<u64>>::Error: Display,
    <T as TryFrom<i64>>::Error: Display,
    <T as FromStr>::Err: Display,
{
    type Value = T;

    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        formatter.write_str("an integer or string")
    }

    fn visit_u64<E>(self, v: u64) -> Result<Self::Value, E>
    where
        E: serde::de::Error,
    {
        T::try_from(v).map_err(serde::de::Error::custom)
    }

    fn visit_i64<E>(self, v: i64) -> Result<Self::Value, E>
    where
        E: serde::de::Error,
    {
        T::try_from(v).map_err(serde::de::Error::custom)
    }

    fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
    where
        E: serde::de::Error,
    {
        v.parse().map_err(serde::de::Error::custom)
    }
}

fn deserialize_integer_or_string<'de, D, T>(deserializer: D) -> Result<T, D::Error>
where
    D: Deserializer<'de>,
    T: TryFrom<u64> + TryFrom<i64> + FromStr,
    <T as TryFrom<u64>>::Error: Display,
    <T as TryFrom<i64>>::Error: Display,
    <T as FromStr>::Err: Display,
{
    deserializer.deserialize_any(NumberVisitor {
        marker: PhantomData,
    })
}

#[derive(Deserialize, Debug)]
pub struct Struct {
    #[serde(deserialize_with = "deserialize_integer_or_string")]
    pub i: i64,
}

#[test]
fn test() {
    let j = r#" {"i":100} "#;
    println!("{:?}", serde_json::from_str::<Struct>(j).unwrap());

    let j = r#" {"i":"100"} "#;
    println!("{:?}", serde_json::from_str::<Struct>(j).unwrap());
}
<|endoftext|>


<commit_before><commit_msg>:construction: Divide the feature of Todoist<commit_after><|endoftext|>


<commit_before><commit_msg>new file: install.rs<commit_after><|endoftext|>


<commit_before><commit_msg>Add test: Sudoku.<commit_after>//! Sudoku.
//!
//! https://en.wikipedia.org/wiki/Sudoku

extern crate puzzle_solver;

use puzzle_solver::{Puzzle,Solution,Val,VarToken};

const SQRT_SIZE: usize = 3;
const SIZE: usize = 9;
type Board = [[Val; SIZE]; SIZE];

fn make_sudoku(board: &Board) -> (Puzzle, Vec<Vec<VarToken>>) {
    let mut sys = Puzzle::new();
    let vars = sys.new_vars_with_candidates_2d(SIZE, SIZE, &[1,2,3,4,5,6,7,8,9]);

    for y in 0..SIZE {
        sys.all_different(&vars[y]);
    }

    for x in 0..SIZE {
        sys.all_different(vars.iter().map(|row| &row[x]));
    }

    for block in 0..SIZE {
        let x0 = SQRT_SIZE * (block % SQRT_SIZE);
        let y0 = SQRT_SIZE * (block / SQRT_SIZE);
        sys.all_different((0..SIZE).map(|n|
                &vars[y0 + (n / SQRT_SIZE)][x0 + (n % SQRT_SIZE)]));
    }

    for y in 0..SIZE {
        for x in 0..SIZE {
            let value = board[y][x];
            if value != 0 {
                sys.set_value(vars[y][x], value);
            }
        }
    }

    (sys, vars)
}

fn print_sudoku(dict: &Solution, vars: &Vec<Vec<VarToken>>) {
    for y in 0..SIZE {
        if y % SQRT_SIZE == 0 {
            println!();
        }

        for x in 0..SIZE {
            print!("{}{}",
                   if x % SQRT_SIZE == 0 { " " } else { "" },
                   dict[vars[y][x]]);
        }
        println!();
    }
}

fn verify_sudoku(dict: &Solution, vars: &Vec<Vec<VarToken>>, expected: &Board) {
    for y in 0..SIZE {
        for x in 0..SIZE {
            assert_eq!(dict[vars[y][x]], expected[y][x]);
        }
    }
}

#[test]
fn sudoku_hardest() {
    let puzzle = [
        [ 8,0,0,  0,0,0,  0,0,0 ],
        [ 0,0,3,  6,0,0,  0,0,0 ],
        [ 0,7,0,  0,9,0,  2,0,0 ],

        [ 0,5,0,  0,0,7,  0,0,0 ],
        [ 0,0,0,  0,4,5,  7,0,0 ],
        [ 0,0,0,  1,0,0,  0,3,0 ],

        [ 0,0,1,  0,0,0,  0,6,8 ],
        [ 0,0,8,  5,0,0,  0,1,0 ],
        [ 0,9,0,  0,0,0,  4,0,0 ] ];

    let expected = [
        [ 8,1,2,  7,5,3,  6,4,9 ],
        [ 9,4,3,  6,8,2,  1,7,5 ],
        [ 6,7,5,  4,9,1,  2,8,3 ],

        [ 1,5,4,  2,3,7,  8,9,6 ],
        [ 3,6,9,  8,4,5,  7,2,1 ],
        [ 2,8,7,  1,6,9,  5,3,4 ],

        [ 5,2,1,  9,7,4,  3,6,8 ],
        [ 4,3,8,  5,2,6,  9,1,7 ],
        [ 7,9,6,  3,1,8,  4,5,2 ] ];

    let (mut sys, vars) = make_sudoku(&puzzle);
    let solution = sys.solve_any().expect("solution");
    print_sudoku(&solution, &vars);
    verify_sudoku(&solution, &vars, &expected);
    println!("sudoku_hardest: {} guesses", sys.num_guesses());
}

#[test]
fn sudoku_wikipedia() {
    let puzzle = [
        [ 5,3,0,  0,7,0,  0,0,0 ],
        [ 6,0,0,  1,9,5,  0,0,0 ],
        [ 0,9,8,  0,0,0,  0,6,0 ],

        [ 8,0,0,  0,6,0,  0,0,3 ],
        [ 4,0,0,  8,0,3,  0,0,1 ],
        [ 7,0,0,  0,2,0,  0,0,6 ],

        [ 0,6,0,  0,0,0,  2,8,0 ],
        [ 0,0,0,  4,1,9,  0,0,5 ],
        [ 0,0,0,  0,8,0,  0,7,9 ] ];

    let expected = [
        [ 5,3,4,  6,7,8,  9,1,2 ],
        [ 6,7,2,  1,9,5,  3,4,8 ],
        [ 1,9,8,  3,4,2,  5,6,7 ],

        [ 8,5,9,  7,6,1,  4,2,3 ],
        [ 4,2,6,  8,5,3,  7,9,1 ],
        [ 7,1,3,  9,2,4,  8,5,6 ],

        [ 9,6,1,  5,3,7,  2,8,4 ],
        [ 2,8,7,  4,1,9,  6,3,5 ],
        [ 3,4,5,  2,8,6,  1,7,9 ] ];

    let (mut sys, vars) = make_sudoku(&puzzle);
    let solution = sys.solve_any().expect("solution");
    print_sudoku(&solution, &vars);
    verify_sudoku(&solution, &vars, &expected);
    println!("sudoku_wikipedia: {} guesses", sys.num_guesses());
}
<|endoftext|>


<commit_before><commit_msg>refactor session::Event<commit_after><|endoftext|>


<commit_before><commit_msg>fetch: rename hash checking to integrity checking<commit_after><|endoftext|>


<commit_before><commit_msg>remove unused tuple<commit_after><|endoftext|>


<commit_before><commit_msg>Minor refactor of cuboid-cuboid contact<commit_after><|endoftext|>


<commit_before><commit_msg>Remove unused method<commit_after><|endoftext|>


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

//! Primitive traits and marker types representing basic 'kinds' of types.
//!
//! Rust types can be classified in various useful ways according to
//! intrinsic properties of the type. These classifications, often called
//! 'kinds', are represented as traits.
//!
//! They cannot be implemented by user code, but are instead implemented
//! by the compiler automatically for the types to which they apply.
//!
//! Marker types are special types that are used with unsafe code to
//! inform the compiler of special constraints. Marker types should
//! only be needed when you are creating an abstraction that is
//! implemented using unsafe code. In that case, you may want to embed
//! some of the marker types below into your type.

#![stable]

use clone::Clone;

/// Types able to be transferred across task boundaries.
#[unstable = "will be overhauled with new lifetime rules; see RFC 458"]
#[lang="send"]
pub unsafe trait Send: 'static {
    // empty.
}

/// Types with a constant size known at compile-time.
#[stable]
#[lang="sized"]
pub trait Sized {
    // Empty.
}

/// Types that can be copied by simply copying bits (i.e. `memcpy`).
#[stable]
#[lang="copy"]
pub trait Copy {
    // Empty.
}

/// Types that can be safely shared between tasks when aliased.
///
/// The precise definition is: a type `T` is `Sync` if `&T` is
/// thread-safe. In other words, there is no possibility of data races
/// when passing `&T` references between tasks.
///
/// As one would expect, primitive types like `u8` and `f64` are all
/// `Sync`, and so are simple aggregate types containing them (like
/// tuples, structs and enums). More instances of basic `Sync` types
/// include "immutable" types like `&T` and those with simple
/// inherited mutability, such as `Box<T>`, `Vec<T>` and most other
/// collection types. (Generic parameters need to be `Sync` for their
/// container to be `Sync`.)
///
/// A somewhat surprising consequence of the definition is `&mut T` is
/// `Sync` (if `T` is `Sync`) even though it seems that it might
/// provide unsynchronised mutation. The trick is a mutable reference
/// stored in an aliasable reference (that is, `& &mut T`) becomes
/// read-only, as if it were a `& &T`, hence there is no risk of a data
/// race.
///
/// Types that are not `Sync` are those that have "interior
/// mutability" in a non-thread-safe way, such as `Cell` and `RefCell`
/// in `std::cell`. These types allow for mutation of their contents
/// even when in an immutable, aliasable slot, e.g. the contents of
/// `&Cell<T>` can be `.set`, and do not ensure data races are
/// impossible, hence they cannot be `Sync`. A higher level example
/// of a non-`Sync` type is the reference counted pointer
/// `std::rc::Rc`, because any reference `&Rc<T>` can clone a new
/// reference, which modifies the reference counts in a non-atomic
/// way.
///
/// For cases when one does need thread-safe interior mutability,
/// types like the atomics in `std::sync` and `Mutex` & `RWLock` in
/// the `sync` crate do ensure that any mutation cannot cause data
/// races.  Hence these types are `Sync`.
///
/// Users writing their own types with interior mutability (or anything
/// else that is not thread-safe) should use the `NoSync` marker type
/// (from `std::marker`) to ensure that the compiler doesn't
/// consider the user-defined type to be `Sync`.  Any types with
/// interior mutability must also use the `std::cell::UnsafeCell` wrapper
/// around the value(s) which can be mutated when behind a `&`
/// reference; not doing this is undefined behaviour (for example,
/// `transmute`-ing from `&T` to `&mut T` is illegal).
#[unstable = "will be overhauled with new lifetime rules; see RFC 458"]
#[lang="sync"]
pub unsafe trait Sync {
    // Empty
}

/// A marker type whose type parameter `T` is considered to be
/// covariant with respect to the type itself. This is (typically)
/// used to indicate that an instance of the type `T` is being stored
/// into memory and read from, even though that may not be apparent.
///
/// For more information about variance, refer to this Wikipedia
/// article <http://en.wikipedia.org/wiki/Variance_%28computer_science%29>.
///
/// *Note:* It is very unusual to have to add a covariant constraint.
/// If you are not sure, you probably want to use `InvariantType`.
///
/// # Example
///
/// Given a struct `S` that includes a type parameter `T`
/// but does not actually *reference* that type parameter:
///
/// ```ignore
/// use std::mem;
///
/// struct S<T> { x: *() }
/// fn get<T>(s: &S<T>) -> T {
///    unsafe {
///        let x: *T = mem::transmute(s.x);
///        *x
///    }
/// }
/// ```
///
/// The type system would currently infer that the value of
/// the type parameter `T` is irrelevant, and hence a `S<int>` is
/// a subtype of `S<Box<int>>` (or, for that matter, `S<U>` for
/// any `U`). But this is incorrect because `get()` converts the
/// `*()` into a `*T` and reads from it. Therefore, we should include the
/// a marker field `CovariantType<T>` to inform the type checker that
/// `S<T>` is a subtype of `S<U>` if `T` is a subtype of `U`
/// (for example, `S<&'static int>` is a subtype of `S<&'a int>`
/// for some lifetime `'a`, but not the other way around).
#[unstable = "likely to change with new variance strategy"]
#[lang="covariant_type"]
#[derive(PartialEq, Eq, PartialOrd, Ord)]
pub struct CovariantType<T: ?Sized>;

impl<T: ?Sized> Copy for CovariantType<T> {}
impl<T: ?Sized> Clone for CovariantType<T> {
    fn clone(&self) -> CovariantType<T> { *self }
}

/// A marker type whose type parameter `T` is considered to be
/// contravariant with respect to the type itself. This is (typically)
/// used to indicate that an instance of the type `T` will be consumed
/// (but not read from), even though that may not be apparent.
///
/// For more information about variance, refer to this Wikipedia
/// article <http://en.wikipedia.org/wiki/Variance_%28computer_science%29>.
///
/// *Note:* It is very unusual to have to add a contravariant constraint.
/// If you are not sure, you probably want to use `InvariantType`.
///
/// # Example
///
/// Given a struct `S` that includes a type parameter `T`
/// but does not actually *reference* that type parameter:
///
/// ```
/// use std::mem;
///
/// struct S<T> { x: *const () }
/// fn get<T>(s: &S<T>, v: T) {
///    unsafe {
///        let x: fn(T) = mem::transmute(s.x);
///        x(v)
///    }
/// }
/// ```
///
/// The type system would currently infer that the value of
/// the type parameter `T` is irrelevant, and hence a `S<int>` is
/// a subtype of `S<Box<int>>` (or, for that matter, `S<U>` for
/// any `U`). But this is incorrect because `get()` converts the
/// `*()` into a `fn(T)` and then passes a value of type `T` to it.
///
/// Supplying a `ContravariantType` marker would correct the
/// problem, because it would mark `S` so that `S<T>` is only a
/// subtype of `S<U>` if `U` is a subtype of `T`; given that the
/// function requires arguments of type `T`, it must also accept
/// arguments of type `U`, hence such a conversion is safe.
#[unstable = "likely to change with new variance strategy"]
#[lang="contravariant_type"]
#[derive(PartialEq, Eq, PartialOrd, Ord)]
pub struct ContravariantType<T: ?Sized>;

impl<T: ?Sized> Copy for ContravariantType<T> {}
impl<T: ?Sized> Clone for ContravariantType<T> {
    fn clone(&self) -> ContravariantType<T> { *self }
}

/// A marker type whose type parameter `T` is considered to be
/// invariant with respect to the type itself. This is (typically)
/// used to indicate that instances of the type `T` may be read or
/// written, even though that may not be apparent.
///
/// For more information about variance, refer to this Wikipedia
/// article <http://en.wikipedia.org/wiki/Variance_%28computer_science%29>.
///
/// # Example
///
/// The Cell type is an example which uses unsafe code to achieve
/// "interior" mutability:
///
/// ```
/// pub struct Cell<T> { value: T }
/// # fn main() {}
/// ```
///
/// The type system would infer that `value` is only read here and
/// never written, but in fact `Cell` uses unsafe code to achieve
/// interior mutability.
#[unstable = "likely to change with new variance strategy"]
#[lang="invariant_type"]
#[derive(PartialEq, Eq, PartialOrd, Ord)]
pub struct InvariantType<T: ?Sized>;

#[unstable = "likely to change with new variance strategy"]
impl<T: ?Sized> Copy for InvariantType<T> {}
#[unstable = "likely to change with new variance strategy"]
impl<T: ?Sized> Clone for InvariantType<T> {
    fn clone(&self) -> InvariantType<T> { *self }
}

/// As `CovariantType`, but for lifetime parameters. Using
/// `CovariantLifetime<'a>` indicates that it is ok to substitute
/// a *longer* lifetime for `'a` than the one you originally
/// started with (e.g., you could convert any lifetime `'foo` to
/// `'static`). You almost certainly want `ContravariantLifetime`
/// instead, or possibly `InvariantLifetime`. The only case where
/// it would be appropriate is that you have a (type-casted, and
/// hence hidden from the type system) function pointer with a
/// signature like `fn(&'a T)` (and no other uses of `'a`). In
/// this case, it is ok to substitute a larger lifetime for `'a`
/// (e.g., `fn(&'static T)`), because the function is only
/// becoming more selective in terms of what it accepts as
/// argument.
///
/// For more information about variance, refer to this Wikipedia
/// article <http://en.wikipedia.org/wiki/Variance_%28computer_science%29>.
#[unstable = "likely to change with new variance strategy"]
#[lang="covariant_lifetime"]
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct CovariantLifetime<'a>;

/// As `ContravariantType`, but for lifetime parameters. Using
/// `ContravariantLifetime<'a>` indicates that it is ok to
/// substitute a *shorter* lifetime for `'a` than the one you
/// originally started with (e.g., you could convert `'static` to
/// any lifetime `'foo`). This is appropriate for cases where you
/// have an unsafe pointer that is actually a pointer into some
/// memory with lifetime `'a`, and thus you want to limit the
/// lifetime of your data structure to `'a`. An example of where
/// this is used is the iterator for vectors.
///
/// For more information about variance, refer to this Wikipedia
/// article <http://en.wikipedia.org/wiki/Variance_%28computer_science%29>.
#[unstable = "likely to change with new variance strategy"]
#[lang="contravariant_lifetime"]
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct ContravariantLifetime<'a>;

/// As `InvariantType`, but for lifetime parameters. Using
/// `InvariantLifetime<'a>` indicates that it is not ok to
/// substitute any other lifetime for `'a` besides its original
/// value. This is appropriate for cases where you have an unsafe
/// pointer that is actually a pointer into memory with lifetime `'a`,
/// and this pointer is itself stored in an inherently mutable
/// location (such as a `Cell`).
#[unstable = "likely to change with new variance strategy"]
#[lang="invariant_lifetime"]
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct InvariantLifetime<'a>;

/// A type which is considered "not sendable", meaning that it cannot
/// be safely sent between tasks, even if it is owned. This is
/// typically embedded in other types, such as `Gc`, to ensure that
/// their instances remain thread-local.
#[unstable = "likely to change with new variance strategy"]
#[lang="no_send_bound"]
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct NoSend;

/// A type which is considered "not POD", meaning that it is not
/// implicitly copyable. This is typically embedded in other types to
/// ensure that they are never copied, even if they lack a destructor.
#[unstable = "likely to change with new variance strategy"]
#[lang="no_copy_bound"]
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord)]
#[allow(missing_copy_implementations)]
pub struct NoCopy;

/// A type which is considered "not sync", meaning that
/// its contents are not threadsafe, hence they cannot be
/// shared between tasks.
#[unstable = "likely to change with new variance strategy"]
#[lang="no_sync_bound"]
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct NoSync;

/// A type which is considered managed by the GC. This is typically
/// embedded in other types.
#[unstable = "likely to change with new variance strategy"]
#[lang="managed_bound"]
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord)]
#[allow(missing_copy_implementations)]
pub struct Managed;
<commit_msg>Remove NoSend/NoSync<commit_after>// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

//! Primitive traits and marker types representing basic 'kinds' of types.
//!
//! Rust types can be classified in various useful ways according to
//! intrinsic properties of the type. These classifications, often called
//! 'kinds', are represented as traits.
//!
//! They cannot be implemented by user code, but are instead implemented
//! by the compiler automatically for the types to which they apply.
//!
//! Marker types are special types that are used with unsafe code to
//! inform the compiler of special constraints. Marker types should
//! only be needed when you are creating an abstraction that is
//! implemented using unsafe code. In that case, you may want to embed
//! some of the marker types below into your type.

#![stable]

use clone::Clone;

/// Types able to be transferred across task boundaries.
#[unstable = "will be overhauled with new lifetime rules; see RFC 458"]
#[lang="send"]
pub unsafe trait Send: 'static {
    // empty.
}

/// Types with a constant size known at compile-time.
#[stable]
#[lang="sized"]
pub trait Sized {
    // Empty.
}

/// Types that can be copied by simply copying bits (i.e. `memcpy`).
#[stable]
#[lang="copy"]
pub trait Copy {
    // Empty.
}

/// Types that can be safely shared between tasks when aliased.
///
/// The precise definition is: a type `T` is `Sync` if `&T` is
/// thread-safe. In other words, there is no possibility of data races
/// when passing `&T` references between tasks.
///
/// As one would expect, primitive types like `u8` and `f64` are all
/// `Sync`, and so are simple aggregate types containing them (like
/// tuples, structs and enums). More instances of basic `Sync` types
/// include "immutable" types like `&T` and those with simple
/// inherited mutability, such as `Box<T>`, `Vec<T>` and most other
/// collection types. (Generic parameters need to be `Sync` for their
/// container to be `Sync`.)
///
/// A somewhat surprising consequence of the definition is `&mut T` is
/// `Sync` (if `T` is `Sync`) even though it seems that it might
/// provide unsynchronised mutation. The trick is a mutable reference
/// stored in an aliasable reference (that is, `& &mut T`) becomes
/// read-only, as if it were a `& &T`, hence there is no risk of a data
/// race.
///
/// Types that are not `Sync` are those that have "interior
/// mutability" in a non-thread-safe way, such as `Cell` and `RefCell`
/// in `std::cell`. These types allow for mutation of their contents
/// even when in an immutable, aliasable slot, e.g. the contents of
/// `&Cell<T>` can be `.set`, and do not ensure data races are
/// impossible, hence they cannot be `Sync`. A higher level example
/// of a non-`Sync` type is the reference counted pointer
/// `std::rc::Rc`, because any reference `&Rc<T>` can clone a new
/// reference, which modifies the reference counts in a non-atomic
/// way.
///
/// For cases when one does need thread-safe interior mutability,
/// types like the atomics in `std::sync` and `Mutex` & `RWLock` in
/// the `sync` crate do ensure that any mutation cannot cause data
/// races.  Hence these types are `Sync`.
///
/// Users writing their own types with interior mutability (or anything
/// else that is not thread-safe) should use the `NoSync` marker type
/// (from `std::marker`) to ensure that the compiler doesn't
/// consider the user-defined type to be `Sync`.  Any types with
/// interior mutability must also use the `std::cell::UnsafeCell` wrapper
/// around the value(s) which can be mutated when behind a `&`
/// reference; not doing this is undefined behaviour (for example,
/// `transmute`-ing from `&T` to `&mut T` is illegal).
#[unstable = "will be overhauled with new lifetime rules; see RFC 458"]
#[lang="sync"]
pub unsafe trait Sync {
    // Empty
}

/// A marker type whose type parameter `T` is considered to be
/// covariant with respect to the type itself. This is (typically)
/// used to indicate that an instance of the type `T` is being stored
/// into memory and read from, even though that may not be apparent.
///
/// For more information about variance, refer to this Wikipedia
/// article <http://en.wikipedia.org/wiki/Variance_%28computer_science%29>.
///
/// *Note:* It is very unusual to have to add a covariant constraint.
/// If you are not sure, you probably want to use `InvariantType`.
///
/// # Example
///
/// Given a struct `S` that includes a type parameter `T`
/// but does not actually *reference* that type parameter:
///
/// ```ignore
/// use std::mem;
///
/// struct S<T> { x: *() }
/// fn get<T>(s: &S<T>) -> T {
///    unsafe {
///        let x: *T = mem::transmute(s.x);
///        *x
///    }
/// }
/// ```
///
/// The type system would currently infer that the value of
/// the type parameter `T` is irrelevant, and hence a `S<int>` is
/// a subtype of `S<Box<int>>` (or, for that matter, `S<U>` for
/// any `U`). But this is incorrect because `get()` converts the
/// `*()` into a `*T` and reads from it. Therefore, we should include the
/// a marker field `CovariantType<T>` to inform the type checker that
/// `S<T>` is a subtype of `S<U>` if `T` is a subtype of `U`
/// (for example, `S<&'static int>` is a subtype of `S<&'a int>`
/// for some lifetime `'a`, but not the other way around).
#[unstable = "likely to change with new variance strategy"]
#[lang="covariant_type"]
#[derive(PartialEq, Eq, PartialOrd, Ord)]
pub struct CovariantType<T: ?Sized>;

impl<T: ?Sized> Copy for CovariantType<T> {}
impl<T: ?Sized> Clone for CovariantType<T> {
    fn clone(&self) -> CovariantType<T> { *self }
}

/// A marker type whose type parameter `T` is considered to be
/// contravariant with respect to the type itself. This is (typically)
/// used to indicate that an instance of the type `T` will be consumed
/// (but not read from), even though that may not be apparent.
///
/// For more information about variance, refer to this Wikipedia
/// article <http://en.wikipedia.org/wiki/Variance_%28computer_science%29>.
///
/// *Note:* It is very unusual to have to add a contravariant constraint.
/// If you are not sure, you probably want to use `InvariantType`.
///
/// # Example
///
/// Given a struct `S` that includes a type parameter `T`
/// but does not actually *reference* that type parameter:
///
/// ```
/// use std::mem;
///
/// struct S<T> { x: *const () }
/// fn get<T>(s: &S<T>, v: T) {
///    unsafe {
///        let x: fn(T) = mem::transmute(s.x);
///        x(v)
///    }
/// }
/// ```
///
/// The type system would currently infer that the value of
/// the type parameter `T` is irrelevant, and hence a `S<int>` is
/// a subtype of `S<Box<int>>` (or, for that matter, `S<U>` for
/// any `U`). But this is incorrect because `get()` converts the
/// `*()` into a `fn(T)` and then passes a value of type `T` to it.
///
/// Supplying a `ContravariantType` marker would correct the
/// problem, because it would mark `S` so that `S<T>` is only a
/// subtype of `S<U>` if `U` is a subtype of `T`; given that the
/// function requires arguments of type `T`, it must also accept
/// arguments of type `U`, hence such a conversion is safe.
#[unstable = "likely to change with new variance strategy"]
#[lang="contravariant_type"]
#[derive(PartialEq, Eq, PartialOrd, Ord)]
pub struct ContravariantType<T: ?Sized>;

impl<T: ?Sized> Copy for ContravariantType<T> {}
impl<T: ?Sized> Clone for ContravariantType<T> {
    fn clone(&self) -> ContravariantType<T> { *self }
}

/// A marker type whose type parameter `T` is considered to be
/// invariant with respect to the type itself. This is (typically)
/// used to indicate that instances of the type `T` may be read or
/// written, even though that may not be apparent.
///
/// For more information about variance, refer to this Wikipedia
/// article <http://en.wikipedia.org/wiki/Variance_%28computer_science%29>.
///
/// # Example
///
/// The Cell type is an example which uses unsafe code to achieve
/// "interior" mutability:
///
/// ```
/// pub struct Cell<T> { value: T }
/// # fn main() {}
/// ```
///
/// The type system would infer that `value` is only read here and
/// never written, but in fact `Cell` uses unsafe code to achieve
/// interior mutability.
#[unstable = "likely to change with new variance strategy"]
#[lang="invariant_type"]
#[derive(PartialEq, Eq, PartialOrd, Ord)]
pub struct InvariantType<T: ?Sized>;

#[unstable = "likely to change with new variance strategy"]
impl<T: ?Sized> Copy for InvariantType<T> {}
#[unstable = "likely to change with new variance strategy"]
impl<T: ?Sized> Clone for InvariantType<T> {
    fn clone(&self) -> InvariantType<T> { *self }
}

/// As `CovariantType`, but for lifetime parameters. Using
/// `CovariantLifetime<'a>` indicates that it is ok to substitute
/// a *longer* lifetime for `'a` than the one you originally
/// started with (e.g., you could convert any lifetime `'foo` to
/// `'static`). You almost certainly want `ContravariantLifetime`
/// instead, or possibly `InvariantLifetime`. The only case where
/// it would be appropriate is that you have a (type-casted, and
/// hence hidden from the type system) function pointer with a
/// signature like `fn(&'a T)` (and no other uses of `'a`). In
/// this case, it is ok to substitute a larger lifetime for `'a`
/// (e.g., `fn(&'static T)`), because the function is only
/// becoming more selective in terms of what it accepts as
/// argument.
///
/// For more information about variance, refer to this Wikipedia
/// article <http://en.wikipedia.org/wiki/Variance_%28computer_science%29>.
#[unstable = "likely to change with new variance strategy"]
#[lang="covariant_lifetime"]
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct CovariantLifetime<'a>;

/// As `ContravariantType`, but for lifetime parameters. Using
/// `ContravariantLifetime<'a>` indicates that it is ok to
/// substitute a *shorter* lifetime for `'a` than the one you
/// originally started with (e.g., you could convert `'static` to
/// any lifetime `'foo`). This is appropriate for cases where you
/// have an unsafe pointer that is actually a pointer into some
/// memory with lifetime `'a`, and thus you want to limit the
/// lifetime of your data structure to `'a`. An example of where
/// this is used is the iterator for vectors.
///
/// For more information about variance, refer to this Wikipedia
/// article <http://en.wikipedia.org/wiki/Variance_%28computer_science%29>.
#[unstable = "likely to change with new variance strategy"]
#[lang="contravariant_lifetime"]
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct ContravariantLifetime<'a>;

/// As `InvariantType`, but for lifetime parameters. Using
/// `InvariantLifetime<'a>` indicates that it is not ok to
/// substitute any other lifetime for `'a` besides its original
/// value. This is appropriate for cases where you have an unsafe
/// pointer that is actually a pointer into memory with lifetime `'a`,
/// and this pointer is itself stored in an inherently mutable
/// location (such as a `Cell`).
#[unstable = "likely to change with new variance strategy"]
#[lang="invariant_lifetime"]
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct InvariantLifetime<'a>;

/// A type which is considered "not sendable", meaning that it cannot
/// be safely sent between tasks, even if it is owned. This is
/// typically embedded in other types, such as `Gc`, to ensure that
/// their instances remain thread-local.
#[unstable = "likely to change with new variance strategy"]
#[lang="no_send_bound"]
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
#[cfg(stage0)] // NOTE remove impl after next snapshot
pub struct NoSend;

/// A type which is considered "not POD", meaning that it is not
/// implicitly copyable. This is typically embedded in other types to
/// ensure that they are never copied, even if they lack a destructor.
#[unstable = "likely to change with new variance strategy"]
#[lang="no_copy_bound"]
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord)]
#[allow(missing_copy_implementations)]
pub struct NoCopy;

/// A type which is considered "not sync", meaning that
/// its contents are not threadsafe, hence they cannot be
/// shared between tasks.
#[unstable = "likely to change with new variance strategy"]
#[lang="no_sync_bound"]
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
#[cfg(stage0)] // NOTE remove impl after next snapshot
pub struct NoSync;

/// A type which is considered managed by the GC. This is typically
/// embedded in other types.
#[unstable = "likely to change with new variance strategy"]
#[lang="managed_bound"]
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord)]
#[allow(missing_copy_implementations)]
pub struct Managed;
<|endoftext|>


<commit_before>/*!
 * Operations on the ubiquitous `option` type.
 *
 * Type `option` represents an optional value.
 *
 * Every `option<T>` value can either be `some(T)` or `none`. Where in other
 * languages you might use a nullable type, in Rust you would use an option
 * type.
 */

/// The option type
enum option<T> {
    none,
    some(T),
}

pure fn get<T: copy>(opt: option<T>) -> T {
    /*!
     * Gets the value out of an option
     *
     * # Failure
     *
     * Fails if the value equals `none`
     */

    alt opt { some(x) { ret x; } none { fail ~"option none"; } }
}

pure fn expect<T: copy>(opt: option<T>, reason: ~str) -> T {
    #[doc = "
    Gets the value out of an option, printing a specified message on failure

    # Failure

    Fails if the value equals `none`
    "];
    alt opt { some(x) { x } none { fail reason; } }
}

pure fn map<T, U>(opt: option<T>, f: fn(T) -> U) -> option<U> {
    //! Maps a `some` value from one type to another

    alt opt { some(x) { some(f(x)) } none { none } }
}

pure fn map_consume<T, U>(-opt: option<T>, f: fn(-T) -> U) -> option<U> {
    /*!
     * As `map`, but consumes the option and gives `f` ownership to avoid
     * copying.
     */
    if opt.is_some() { some(f(option::unwrap(opt))) } else { none }
}

pure fn chain<T, U>(opt: option<T>, f: fn(T) -> option<U>) -> option<U> {
    /*!
     * Update an optional value by optionally running its content through a
     * function that returns an option.
     */

    alt opt { some(x) { f(x) } none { none } }
}

#[inline(always)]
pure fn while_some<T>(+x: option<T>, blk: fn(+T) -> option<T>) {
    //! Applies a function zero or more times until the result is none.

    let mut opt <- x;
    while opt.is_some() {
        opt = blk(unwrap(opt));
    }
}

pure fn is_none<T>(opt: option<T>) -> bool {
    //! Returns true if the option equals `none`

    alt opt { none { true } some(_) { false } }
}

pure fn is_some<T>(opt: option<T>) -> bool {
    //! Returns true if the option contains some value

    !is_none(opt)
}

pure fn get_default<T: copy>(opt: option<T>, def: T) -> T {
    //! Returns the contained value or a default

    alt opt { some(x) { x } none { def } }
}

pure fn map_default<T, U: copy>(opt: option<T>, def: U, f: fn(T) -> U) -> U {
    //! Applies a function to the contained value or returns a default

    alt opt { none { def } some(t) { f(t) } }
}

pure fn iter<T>(opt: option<T>, f: fn(T)) {
    //! Performs an operation on the contained value or does nothing

    alt opt { none { } some(t) { f(t); } }
}

#[inline(always)]
pure fn unwrap<T>(-opt: option<T>) -> T {
    /*!
     * Moves a value out of an option type and returns it.
     *
     * Useful primarily for getting strings, vectors and unique pointers out
     * of option types without copying them.
     */

    unsafe {
        let addr = alt opt {
          some(x) { ptr::addr_of(x) }
          none { fail ~"option none" }
        };
        let liberated_value = unsafe::reinterpret_cast(*addr);
        unsafe::forget(opt);
        ret liberated_value;
    }
}

pure fn unwrap_expect<T>(-opt: option<T>, reason: ~str) -> T {
    //! As unwrap, but with a specified failure message.
    if opt.is_none() { fail reason; }
    unwrap(opt)
}

impl extensions<T> for option<T> {
    /**
     * Update an optional value by optionally running its content through a
     * function that returns an option.
     */
    pure fn chain<U>(f: fn(T) -> option<U>) -> option<U> { chain(self, f) }
    /// Applies a function to the contained value or returns a default
    pure fn map_default<U: copy>(def: U, f: fn(T) -> U) -> U
        { map_default(self, def, f) }
    /// Performs an operation on the contained value or does nothing
    pure fn iter(f: fn(T)) { iter(self, f) }
    /// Returns true if the option equals `none`
    pure fn is_none() -> bool { is_none(self) }
    /// Returns true if the option contains some value
    pure fn is_some() -> bool { is_some(self) }
    /// Maps a `some` value from one type to another
    pure fn map<U>(f: fn(T) -> U) -> option<U> { map(self, f) }
}

impl extensions<T: copy> for option<T> {
    /**
     * Gets the value out of an option
     *
     * # Failure
     *
     * Fails if the value equals `none`
     */
    pure fn get() -> T { get(self) }
    pure fn get_default(def: T) -> T { get_default(self, def) }
    /**
     * Gets the value out of an option, printing a specified message on
     * failure
     *
     * # Failure
     *
     * Fails if the value equals `none`
     */
    pure fn expect(reason: ~str) -> T { expect(self, reason) }
    /// Applies a function zero or more times until the result is none.
    pure fn while_some(blk: fn(+T) -> option<T>) { while_some(self, blk) }
}

#[test]
fn test_unwrap_ptr() {
    let x = ~0;
    let addr_x = ptr::addr_of(*x);
    let opt = some(x);
    let y = unwrap(opt);
    let addr_y = ptr::addr_of(*y);
    assert addr_x == addr_y;
}

#[test]
fn test_unwrap_str() {
    let x = ~"test";
    let addr_x = str::as_buf(x, |buf, _len| ptr::addr_of(buf));
    let opt = some(x);
    let y = unwrap(opt);
    let addr_y = str::as_buf(y, |buf, _len| ptr::addr_of(buf));
    assert addr_x == addr_y;
}

#[test]
fn test_unwrap_resource() {
    class r {
       let i: @mut int;
       new(i: @mut int) { self.i = i; }
       drop { *(self.i) += 1; }
    }
    let i = @mut 0;
    {
        let x = r(i);
        let opt = some(x);
        let _y = unwrap(opt);
    }
    assert *i == 1;
}

#[test]
fn test_option_while_some() {
    let mut i = 0;
    do some(10).while_some |j| {
        i += 1;
        if (j > 0) {
            some(j-1)
        } else {
            none
        }
    }
    assert i == 11;
}

// Local Variables:
// mode: rust;
// fill-column: 78;
// indent-tabs-mode: nil
// c-basic-offset: 4
// buffer-file-coding-system: utf-8-unix
// End:
<commit_msg>make option::map_default<T,U> instead of U:copy<commit_after>/*!
 * Operations on the ubiquitous `option` type.
 *
 * Type `option` represents an optional value.
 *
 * Every `option<T>` value can either be `some(T)` or `none`. Where in other
 * languages you might use a nullable type, in Rust you would use an option
 * type.
 */

/// The option type
enum option<T> {
    none,
    some(T),
}

pure fn get<T: copy>(opt: option<T>) -> T {
    /*!
     * Gets the value out of an option
     *
     * # Failure
     *
     * Fails if the value equals `none`
     */

    alt opt { some(x) { ret x; } none { fail ~"option none"; } }
}

pure fn expect<T: copy>(opt: option<T>, reason: ~str) -> T {
    #[doc = "
    Gets the value out of an option, printing a specified message on failure

    # Failure

    Fails if the value equals `none`
    "];
    alt opt { some(x) { x } none { fail reason; } }
}

pure fn map<T, U>(opt: option<T>, f: fn(T) -> U) -> option<U> {
    //! Maps a `some` value from one type to another

    alt opt { some(x) { some(f(x)) } none { none } }
}

pure fn map_consume<T, U>(-opt: option<T>, f: fn(-T) -> U) -> option<U> {
    /*!
     * As `map`, but consumes the option and gives `f` ownership to avoid
     * copying.
     */
    if opt.is_some() { some(f(option::unwrap(opt))) } else { none }
}

pure fn chain<T, U>(opt: option<T>, f: fn(T) -> option<U>) -> option<U> {
    /*!
     * Update an optional value by optionally running its content through a
     * function that returns an option.
     */

    alt opt { some(x) { f(x) } none { none } }
}

#[inline(always)]
pure fn while_some<T>(+x: option<T>, blk: fn(+T) -> option<T>) {
    //! Applies a function zero or more times until the result is none.

    let mut opt <- x;
    while opt.is_some() {
        opt = blk(unwrap(opt));
    }
}

pure fn is_none<T>(opt: option<T>) -> bool {
    //! Returns true if the option equals `none`

    alt opt { none { true } some(_) { false } }
}

pure fn is_some<T>(opt: option<T>) -> bool {
    //! Returns true if the option contains some value

    !is_none(opt)
}

pure fn get_default<T: copy>(opt: option<T>, def: T) -> T {
    //! Returns the contained value or a default

    alt opt { some(x) { x } none { def } }
}

pure fn map_default<T, U>(opt: option<T>, +def: U, f: fn(T) -> U) -> U {
    //! Applies a function to the contained value or returns a default

    alt opt { none { def } some(t) { f(t) } }
}

pure fn iter<T>(opt: option<T>, f: fn(T)) {
    //! Performs an operation on the contained value or does nothing

    alt opt { none { } some(t) { f(t); } }
}

#[inline(always)]
pure fn unwrap<T>(-opt: option<T>) -> T {
    /*!
     * Moves a value out of an option type and returns it.
     *
     * Useful primarily for getting strings, vectors and unique pointers out
     * of option types without copying them.
     */

    unsafe {
        let addr = alt opt {
          some(x) { ptr::addr_of(x) }
          none { fail ~"option none" }
        };
        let liberated_value = unsafe::reinterpret_cast(*addr);
        unsafe::forget(opt);
        ret liberated_value;
    }
}

pure fn unwrap_expect<T>(-opt: option<T>, reason: ~str) -> T {
    //! As unwrap, but with a specified failure message.
    if opt.is_none() { fail reason; }
    unwrap(opt)
}

impl extensions<T> for option<T> {
    /**
     * Update an optional value by optionally running its content through a
     * function that returns an option.
     */
    pure fn chain<U>(f: fn(T) -> option<U>) -> option<U> { chain(self, f) }
    /// Applies a function to the contained value or returns a default
    pure fn map_default<U>(+def: U, f: fn(T) -> U) -> U
        { map_default(self, def, f) }
    /// Performs an operation on the contained value or does nothing
    pure fn iter(f: fn(T)) { iter(self, f) }
    /// Returns true if the option equals `none`
    pure fn is_none() -> bool { is_none(self) }
    /// Returns true if the option contains some value
    pure fn is_some() -> bool { is_some(self) }
    /// Maps a `some` value from one type to another
    pure fn map<U>(f: fn(T) -> U) -> option<U> { map(self, f) }
}

impl extensions<T: copy> for option<T> {
    /**
     * Gets the value out of an option
     *
     * # Failure
     *
     * Fails if the value equals `none`
     */
    pure fn get() -> T { get(self) }
    pure fn get_default(def: T) -> T { get_default(self, def) }
    /**
     * Gets the value out of an option, printing a specified message on
     * failure
     *
     * # Failure
     *
     * Fails if the value equals `none`
     */
    pure fn expect(reason: ~str) -> T { expect(self, reason) }
    /// Applies a function zero or more times until the result is none.
    pure fn while_some(blk: fn(+T) -> option<T>) { while_some(self, blk) }
}

#[test]
fn test_unwrap_ptr() {
    let x = ~0;
    let addr_x = ptr::addr_of(*x);
    let opt = some(x);
    let y = unwrap(opt);
    let addr_y = ptr::addr_of(*y);
    assert addr_x == addr_y;
}

#[test]
fn test_unwrap_str() {
    let x = ~"test";
    let addr_x = str::as_buf(x, |buf, _len| ptr::addr_of(buf));
    let opt = some(x);
    let y = unwrap(opt);
    let addr_y = str::as_buf(y, |buf, _len| ptr::addr_of(buf));
    assert addr_x == addr_y;
}

#[test]
fn test_unwrap_resource() {
    class r {
       let i: @mut int;
       new(i: @mut int) { self.i = i; }
       drop { *(self.i) += 1; }
    }
    let i = @mut 0;
    {
        let x = r(i);
        let opt = some(x);
        let _y = unwrap(opt);
    }
    assert *i == 1;
}

#[test]
fn test_option_while_some() {
    let mut i = 0;
    do some(10).while_some |j| {
        i += 1;
        if (j > 0) {
            some(j-1)
        } else {
            none
        }
    }
    assert i == 11;
}

// Local Variables:
// mode: rust;
// fill-column: 78;
// indent-tabs-mode: nil
// c-basic-offset: 4
// buffer-file-coding-system: utf-8-unix
// End:
<|endoftext|>


<commit_before><commit_msg>rethinking Adapton API, from implementation outwards<commit_after>use std::hash::Hash;
use std::collections::HashMap;
use std::thunk::Invoke;

// "One big memo table" design

pub trait Adapton {
    fn name_of_string (self:&mut Self, String) -> Name ;
    fn name_of_u64 (self:&mut Self, u64) -> Name ;
    fn pair (self: &Self, Name, Name) -> Name ;
    fn fork (self:&mut Self, Name) -> (Name, Name) ;

    fn cell<T:Eq+Hash> (self:&mut Self, ArtId, T) -> Art<T> ;

    fn thunk<Arg:Eq+Hash,T:Eq+Hash>
        (self:&mut Self, id:ArtId, fn_body:Box<Invoke<Arg,T>+'static>, arg:Arg) -> Art<T> ;

    fn force<T:Eq+Hash> (self:&mut Self, Art<T>) -> T ;
}

pub enum Lineage {
    Unknown,
    Pair(Box<Lineage>,Box<Lineage>),
    ForkL(Box<Lineage>),
    ForkR(Box<Lineage>),
    String(String),
    U64(u64),
}

pub struct Name {
    hash : u64,
    lineage : Lineage,
}

pub enum Art<T> {
    Hash(u64),
    Box(Box<T>),
}

pub enum ArtId {
    None,
    Structural,
    Nominal(Name),
}

pub struct AdaptonState {
    mtbl : HashMap<Name, *mut ()>,
}

impl Adapton for AdaptonState {
    fn name_of_string (self:&mut AdaptonState, sym:String) -> Name {
        panic!("")
    }
    fn name_of_u64 (self:&mut AdaptonState, sym:u64) -> Name {
        panic!("")
    }
    fn pair (self: &AdaptonState, fst: Name, snd: Name) -> Name {
        panic!("")
    }
    fn fork (self:&mut AdaptonState, nm:Name) -> (Name, Name) {
        panic!("")
    }
    fn cell<T:Eq+Hash> (self:&mut AdaptonState, id:ArtId, x:T) -> Art<T> {
        panic!("")
    }
    fn thunk<Arg:Eq+Hash,T:Eq+Hash>
        (self:&mut AdaptonState,
         id:ArtId, fn_body:Box<Invoke<Arg,T>+'static>, arg:Arg) -> Art<T>
    {
        panic!("")
    }
    fn force<T:Eq+Hash> (self:&mut AdaptonState, art:Art<T>) -> T {
        panic!("")
    }
}

pub fn main () {

}
<|endoftext|>


<commit_before><commit_msg>Fix typo: substract -> subtract<commit_after><|endoftext|>


<commit_before><commit_msg>style: Remove layout.css.prefixes.device-pixel-ratio-webkit.<commit_after><|endoftext|>


<commit_before><commit_msg>Small correction<commit_after><|endoftext|>


<commit_before><commit_msg>Minor: just move functions<commit_after><|endoftext|>


<commit_before><commit_msg>smbus: stub remaining methods that are in the smbus API<commit_after><|endoftext|>


<commit_before><commit_msg>euler 4<commit_after>// A palindromic number reads the same both ways. The largest palindrome made
// from the product of two 2-digit numbers is 9009 = 91 x 99.
// Find the largest palindrome made from the product of two 3-digit numbers.

fn is_palindrome<T: ToString>(value: T) -> bool {
	let str1 = value.to_string();
	let str2 = str1.chars().rev().collect::<String>();

	str1 == str2
}

fn main() {
	let (mut candidate, mut max) = (1u64, 1u64);

	for i in 1..1000 {
		for j in 1 ..1000 {
			candidate = i * j;
			if is_palindrome(candidate) && candidate > max { max = candidate; }
		}
	}

	println!("{}", max);
}<|endoftext|>


<commit_before><commit_msg>stats: ignore members who left, fix long msgs<commit_after><|endoftext|>


<commit_before><commit_msg>Screens module refactoring<commit_after>use piston_window;

pub trait Screen {
    fn on_input(&mut self, input: &piston_window::Input);
    fn on_draw(&mut self, args: &piston_window::RenderArgs, window: &piston_window::PistonWindow);
    fn on_update(&mut self, args: &piston_window::UpdateArgs);
}<|endoftext|>


<commit_before><commit_msg>Extract trait for MetricKeyFormatter<commit_after><|endoftext|>