<commit_before><commit_msg>Initial.<commit_after>use std::io;
use std::rand::sample;
use std::rand::task_rng;

fn main() {

    //Input
    let mut iInput: (int,int);

    loop {
        match get_initial_input() {
            Some(t) => {
                iInput = t;
                break;
            },
            None => {
                println!("Invalid input");
                continue;
            },
        }
    }

    let size: int = iInput.val0();
    let sizeu: uint = size.to_uint().expect("Failed to parse integer.");

    let mut state: Vec<int> = Vec::from_elem(sizeu*sizeu, 1);
    let count: int = iInput.val1();
    let countu: uint = count.to_uint().expect("Failed to parse integer.");

    //Place mines.
    let mut rng = task_rng();
    let minePositions = sample(&mut rng, range(0,state.len()), countu);

    for c in minePositions.iter() {
        *state.get_mut(*c) = 2;
    }

    loop {

        //Draw
        print_state(state.slice(0,state.len()), sizeu);
        println!("Enter the cell to clear in a x,y format: ")

        //Input
        let input = get_input();
        let xy: (int, int) = match input {
            Some((x,y)) => (x-1,y-1),
            None => {
                println!("Make sure your input is correct.");
                continue;
            }
        };

        let pos: int = size * xy.val1() + xy.val0();
        let uPos = pos.to_uint().expect("Failed to parse pos to uint.");

        //Check rules.
        if !in_bounds(xy,size) {
            println!("That is not a valid cell.");
            continue;
        }

        match *state.get(uPos) {
            0 => println!("Already cleared!"),
            1 => {
                *state.get_mut(uPos) = 0;
                println!("Cleared {0},{1}!", xy.val0()+1, xy.val1()+1);
            },
            2 => {
                println!("You hit a mine! GAMEOVER");
                break;
            }
            _ => println!("Error clearing mine.")
        }

        if check_win(&state) {
            println!("You have won!");
            break;
        }
    }
}

fn print_state(slice: &[int], width: uint) {
    for x in range(1, width*width + 1)
    {
        let state = slice.get(x-1).unwrap();
        match *state {
            0 => print!("  "),
            1 => print!(". "),
            2 => print!(". "),
            _ => print!("? "),
        }

        if x % width == 0 {
            print!("\n");
        }
    }
    print!("\n");
}

fn get_input() -> Option<(int,int)> {

    let result = io::stdin().read_line();
    let string = match result {
        Ok(s) => s,
        Err(_) => return None,
    };

    let mut splitResult = string.as_slice().split(',');
    let mut strings: Vec<&str> = Vec::new();

    for _ in range(0,2) {
        let st = match splitResult.next() {
            Some(s) => s,
            None => {
                return None;
            }
        };
        strings.push(st);
    }

    let xs = *strings.get(0);
    let ys = *strings.get(1);

    let x = from_str::<int>(xs.trim()).unwrap();
    let y = from_str::<int>(ys.trim()).unwrap();

    let xy: (int,int)  = (x, y);

    Some(xy)
}

fn get_initial_input() -> Option<(int,int)>{

    println!("Input the size of the board (5 -= 5x5): ");
    let size: int =  match get_int() {
        Some(i) => i,
        None => return None,
    };

    println!("Input the number of mines: ");
    let count: int = match get_int() {
        Some(i) => i,
        None => return None,
    };

    if count > size*size {
        println!("Too many mines!");
        return None;
    }

    Some( (size, count) )
}

fn get_int() -> Option<int> {

    let result = io::stdin().read_line();
    let string = match result {
        Ok(s) => s,
        Err(_) => return None,
    };
    let final: int = match from_str::<int>(string.as_slice().trim()) {
        Some(s) => s,
        None => return None,
    };
    Some(final)
}

fn in_bounds(b: (int, int), width: int) -> bool {
    match b {
        (x,y) if y<0 || x<0 => return false,
        (x,y) if y>=width || x>=width => return false,
        (_,_) => return true
    }
}

fn check_win(state: &Vec<int>) -> bool {
    let mut win = true;

    for x in state.iter() {
        if  *x == 1 {
            win = false;
        }
    }
    win
}<|endoftext|>


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

macro_rules! items {
    () => {
        type A = ();
        fn a() {}
    }
}

trait Foo {
    type A;
    fn a();
}

impl Foo for () {
    items!();
}

fn main() {

}
<|endoftext|>


<commit_before>/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

use clap::Clap;
use log::{debug, info, LevelFilter};
use std::net::{IpAddr, SocketAddr};
use std::path::PathBuf;
use std::str::FromStr;
use std::time::{Duration, Instant};
use tokio::net::TcpListener;
use tonic::transport::Server;

use rustboard_core::commit::Commit;
use rustboard_core::logdir::LogdirLoader;
use rustboard_core::proto::tensorboard::data;
use rustboard_core::server::DataProviderHandler;

use data::tensor_board_data_provider_server::TensorBoardDataProviderServer;

#[derive(Clap, Debug)]
#[clap(name = "rustboard", version = "0.1.0")]
struct Opts {
    /// Log directory to load
    ///
    /// Directory to recursively scan for event files (files matching the `*tfevents*` glob). This
    /// directory, its descendants, and its event files will be periodically polled for new data.
    #[clap(long)]
    logdir: PathBuf,

    /// Bind to this IP address
    ///
    /// IP address to bind this server to. May be an IPv4 address (e.g., 127.0.0.1 or 0.0.0.0) or
    /// an IPv6 address (e.g., ::1 or ::0).
    #[clap(long, default_value = "::0")]
    host: IpAddr,

    /// Bind to this port
    ///
    /// Port to bind this server to. Use `0` to request an arbitrary free port from the OS.
    #[clap(long, default_value = "6806")]
    port: u16,

    /// Delay between reload cycles (seconds)
    ///
    /// Number of seconds to wait between finishing one load cycle and starting the next one. This
    /// does not include the time for the reload itself.
    #[clap(long, default_value = "5")]
    reload_interval: Seconds,

    /// Use verbose output (-vv for very verbose output)
    #[clap(long = "verbose", short, parse(from_occurrences))]
    verbosity: u32,
}

/// A duration in seconds.
#[derive(Debug, Copy, Clone)]
struct Seconds(u64);
impl FromStr for Seconds {
    type Err = <u64 as FromStr>::Err;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        s.parse().map(Seconds)
    }
}
impl Seconds {
    fn duration(self) -> Duration {
        Duration::from_secs(self.0)
    }
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let opts = Opts::parse();
    init_logging(match opts.verbosity {
        0 => LevelFilter::Warn,
        1 => LevelFilter::Info,
        _ => LevelFilter::max(),
    });
    debug!("Parsed options: {:?}", opts);

    let addr = SocketAddr::new(opts.host, opts.port);
    let listener = TcpListener::bind(addr).await?;
    let bound = listener.local_addr()?;
    eprintln!("listening on {:?}", bound);

    // Leak the commit object, since the Tonic server must have only 'static references. This only
    // leaks the outer commit structure (of constant size), not the pointers to the actual data.
    let commit: &'static Commit = Box::leak(Box::new(Commit::new()));

    std::thread::spawn(move || {
        let mut loader = LogdirLoader::new(commit, opts.logdir);
        loop {
            info!("Starting load cycle");
            let start = Instant::now();
            loader.reload();
            let end = Instant::now();
            info!("Finished load cycle ({:?})", end - start);
            std::thread::sleep(opts.reload_interval.duration());
        }
    });

    let handler = DataProviderHandler { commit };
    Server::builder()
        .add_service(TensorBoardDataProviderServer::new(handler))
        .serve_with_incoming(listener)
        .await?;
    Ok(())
}

/// Installs a logging handler whose behavior is determined by the `RUST_LOG` environment variable
/// (per <https://docs.rs/env_logger> semantics), or by including all logs at `default_log_level`
/// or above if `RUST_LOG_LEVEL` is not given.
fn init_logging(default_log_level: LevelFilter) {
    use env_logger::{Builder, Env};
    Builder::from_env(Env::default().default_filter_or(default_log_level.to_string())).init();
}
<commit_msg>rust: add option to kill server at stdin EOF (#4408)<commit_after>/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

use clap::Clap;
use log::{debug, info, LevelFilter};
use std::io::Read;
use std::net::{IpAddr, SocketAddr};
use std::path::PathBuf;
use std::str::FromStr;
use std::thread;
use std::time::{Duration, Instant};
use tokio::net::TcpListener;
use tonic::transport::Server;

use rustboard_core::commit::Commit;
use rustboard_core::logdir::LogdirLoader;
use rustboard_core::proto::tensorboard::data;
use rustboard_core::server::DataProviderHandler;

use data::tensor_board_data_provider_server::TensorBoardDataProviderServer;

#[derive(Clap, Debug)]
#[clap(name = "rustboard", version = "0.1.0")]
struct Opts {
    /// Log directory to load
    ///
    /// Directory to recursively scan for event files (files matching the `*tfevents*` glob). This
    /// directory, its descendants, and its event files will be periodically polled for new data.
    #[clap(long)]
    logdir: PathBuf,

    /// Bind to this IP address
    ///
    /// IP address to bind this server to. May be an IPv4 address (e.g., 127.0.0.1 or 0.0.0.0) or
    /// an IPv6 address (e.g., ::1 or ::0).
    #[clap(long, default_value = "::0")]
    host: IpAddr,

    /// Bind to this port
    ///
    /// Port to bind this server to. Use `0` to request an arbitrary free port from the OS.
    #[clap(long, default_value = "6806")]
    port: u16,

    /// Delay between reload cycles (seconds)
    ///
    /// Number of seconds to wait between finishing one load cycle and starting the next one. This
    /// does not include the time for the reload itself.
    #[clap(long, default_value = "5")]
    reload_interval: Seconds,

    /// Use verbose output (-vv for very verbose output)
    #[clap(long = "verbose", short, parse(from_occurrences))]
    verbosity: u32,

    /// Kill this server once stdin is closed
    ///
    /// While this server is running, read stdin to end of file and then kill the server. Used to
    /// portably ensure that the server exits when the parent process dies, even due to a crash.
    /// Don't set this if stdin is connected to a tty and the process will be backgrounded, since
    /// then the server will receive `SIGTTIN` and its process will be stopped (in the `SIGSTOP`
    /// sense) but not killed.
    #[clap(long)]
    die_after_stdin: bool,
}

/// A duration in seconds.
#[derive(Debug, Copy, Clone)]
struct Seconds(u64);
impl FromStr for Seconds {
    type Err = <u64 as FromStr>::Err;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        s.parse().map(Seconds)
    }
}
impl Seconds {
    fn duration(self) -> Duration {
        Duration::from_secs(self.0)
    }
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let opts = Opts::parse();
    init_logging(match opts.verbosity {
        0 => LevelFilter::Warn,
        1 => LevelFilter::Info,
        _ => LevelFilter::max(),
    });
    debug!("Parsed options: {:?}", opts);

    if opts.die_after_stdin {
        thread::Builder::new()
            .name("StdinWatcher".to_string())
            .spawn(die_after_stdin)
            .expect("failed to spawn stdin watcher thread");
    }

    let addr = SocketAddr::new(opts.host, opts.port);
    let listener = TcpListener::bind(addr).await?;
    let bound = listener.local_addr()?;
    eprintln!("listening on {:?}", bound);

    // Leak the commit object, since the Tonic server must have only 'static references. This only
    // leaks the outer commit structure (of constant size), not the pointers to the actual data.
    let commit: &'static Commit = Box::leak(Box::new(Commit::new()));

    thread::Builder::new()
        .name("Reloader".to_string())
        .spawn(move || {
            let mut loader = LogdirLoader::new(commit, opts.logdir);
            loop {
                info!("Starting load cycle");
                let start = Instant::now();
                loader.reload();
                let end = Instant::now();
                info!("Finished load cycle ({:?})", end - start);
                thread::sleep(opts.reload_interval.duration());
            }
        })
        .expect("failed to spawn reloader thread");

    let handler = DataProviderHandler { commit };
    Server::builder()
        .add_service(TensorBoardDataProviderServer::new(handler))
        .serve_with_incoming(listener)
        .await?;
    Ok(())
}

/// Installs a logging handler whose behavior is determined by the `RUST_LOG` environment variable
/// (per <https://docs.rs/env_logger> semantics), or by including all logs at `default_log_level`
/// or above if `RUST_LOG_LEVEL` is not given.
fn init_logging(default_log_level: LevelFilter) {
    use env_logger::{Builder, Env};
    Builder::from_env(Env::default().default_filter_or(default_log_level.to_string())).init();
}

/// Locks stdin and reads it to EOF, then exits the process.
fn die_after_stdin() {
    let stdin = std::io::stdin();
    let stdin_lock = stdin.lock();
    for _ in stdin_lock.bytes() {}
    info!("Stdin closed; exiting");
    std::process::exit(0);
}
<|endoftext|>


<commit_before>use audio::ac97::*;
use audio::intelhda::*;

use common::debug::*;
use common::queue::*;
use common::vec::*;

use drivers::pciconfig::*;

use network::intel8254x::*;
use network::rtl8139::*;

use programs::session::Session;

use schemes::file::*;

use usb::ehci::*;
use usb::uhci::*;
use usb::xhci::*;

/// PCI device
pub unsafe fn pci_device(session: &mut Session,
                         mut pci: PCIConfig,
                         class_id: u32,
                         subclass_id: u32,
                         interface_id: u32,
                         vendor_code: u32,
                         device_code: u32) {
    if class_id == 0x01 && subclass_id == 0x01 {
        if let Some(module) = FileScheme::new(pci) {
            session.items.push(module);
        }
    } else if class_id == 0x0C && subclass_id == 0x03 {
        if interface_id == 0x30 {
            let base = pci.read(0x10) as usize;

            let module = box XHCI {
                pci: pci,
                base: base & 0xFFFFFFF0,
                memory_mapped: base & 1 == 0,
                irq: pci.read(0x3C) as u8 & 0xF,
            };
            module.init();
            session.items.push(module);
        } else if interface_id == 0x20 {
            let base = pci.read(0x10) as usize;

            let mut module = box EHCI {
                pci: pci,
                base: base & 0xFFFFFFF0,
                memory_mapped: base & 1 == 0,
                irq: pci.read(0x3C) as u8 & 0xF,
            };
            module.init();
            session.items.push(module);
        } else if interface_id == 0x10 {
            let base = pci.read(0x10) as usize;

            d("OHCI Controller on ");
            dh(base & 0xFFFFFFF0);
            dl();
        } else if interface_id == 0x00 {
            session.items.push(UHCI::new(pci));
        } else {
            d("Unknown USB interface version\n");
        }
    } else {
        match vendor_code {
            0x10EC => match device_code { // REALTEK
                0x8139 => {
                    session.items.push(RTL8139::new(pci));
                }
                _ => (),
            },
            0x8086 => match device_code { // INTEL
                0x100E => {
                    let base = pci.read(0x10) as usize;
                    let mut module = box Intel8254x {
                        pci: pci,
                        base: base & 0xFFFFFFF0,
                        memory_mapped: base & 1 == 0,
                        irq: pci.read(0x3C) as u8 & 0xF,
                        resources: Vec::new(),
                        inbound: Queue::new(),
                        outbound: Queue::new(),
                    };
                    module.init();
                    session.items.push(module);
                }
                0x2415 => session.items.push(AC97::new(pci)),
                0x24C5 => session.items.push(AC97::new(pci)),
                0x2668 => {
                    let base = pci.read(0x10) as usize;
                    let mut module = box IntelHDA {
                        pci: pci,
                        base: base & 0xFFFFFFF0,
                        memory_mapped: base & 1 == 0,
                        irq: pci.read(0x3C) as u8 & 0xF,
                    };
                    module.init();
                    session.items.push(module);
                }
                _ => (),
            },
            _ => (),
        }
    }
}

/// Initialize PCI session
pub unsafe fn pci_init(session: &mut Session) {
    for bus in 0..256 {
        for slot in 0..32 {
            for func in 0..8 {
                let mut pci = PCIConfig::new(bus as u8, slot as u8, func as u8);
                let id = pci.read(0);

                if (id & 0xFFFF) != 0xFFFF {
                    let class_id = pci.read(8);

                    d("Bus ");
                    dd(bus);
                    d(" Slot ");
                    dd(slot);
                    d(" Function ");
                    dd(func);
                    d(": ");
                    dh(id as usize);
                    d(", ");
                    dh(class_id as usize);

                    for i in 0..6 {
                        let bar = pci.read(i * 4 + 0x10);
                        if bar > 0 {
                            d(" BAR");
                            dd(i as usize);
                            d(": ");
                            dh(bar as usize);
                        }
                    }

                    dl();

                    pci_device(session,
                               pci,
                               (class_id >> 24) & 0xFF,
                               (class_id >> 16) & 0xFF,
                               (class_id >> 8) & 0xFF,
                               id & 0xFFFF,
                               (id >> 16) & 0xFFFF);
                }
            }
        }
    }
}
<commit_msg>Show size of BAR's<commit_after>use audio::ac97::*;
use audio::intelhda::*;

use common::debug::*;
use common::queue::*;
use common::vec::*;

use drivers::pciconfig::*;

use network::intel8254x::*;
use network::rtl8139::*;

use programs::session::Session;

use schemes::file::*;

use usb::ehci::*;
use usb::uhci::*;
use usb::xhci::*;

/// PCI device
pub unsafe fn pci_device(session: &mut Session,
                         mut pci: PCIConfig,
                         class_id: u32,
                         subclass_id: u32,
                         interface_id: u32,
                         vendor_code: u32,
                         device_code: u32) {
    if class_id == 0x01 && subclass_id == 0x01 {
        if let Some(module) = FileScheme::new(pci) {
            session.items.push(module);
        }
    } else if class_id == 0x0C && subclass_id == 0x03 {
        if interface_id == 0x30 {
            let base = pci.read(0x10) as usize;

            let module = box XHCI {
                pci: pci,
                base: base & 0xFFFFFFF0,
                memory_mapped: base & 1 == 0,
                irq: pci.read(0x3C) as u8 & 0xF,
            };
            module.init();
            session.items.push(module);
        } else if interface_id == 0x20 {
            let base = pci.read(0x10) as usize;

            let mut module = box EHCI {
                pci: pci,
                base: base & 0xFFFFFFF0,
                memory_mapped: base & 1 == 0,
                irq: pci.read(0x3C) as u8 & 0xF,
            };
            module.init();
            session.items.push(module);
        } else if interface_id == 0x10 {
            let base = pci.read(0x10) as usize;

            d("OHCI Controller on ");
            dh(base & 0xFFFFFFF0);
            dl();
        } else if interface_id == 0x00 {
            session.items.push(UHCI::new(pci));
        } else {
            d("Unknown USB interface version\n");
        }
    } else {
        match vendor_code {
            0x10EC => match device_code { // REALTEK
                0x8139 => {
                    session.items.push(RTL8139::new(pci));
                }
                _ => (),
            },
            0x8086 => match device_code { // INTEL
                0x100E => {
                    let base = pci.read(0x10) as usize;
                    let mut module = box Intel8254x {
                        pci: pci,
                        base: base & 0xFFFFFFF0,
                        memory_mapped: base & 1 == 0,
                        irq: pci.read(0x3C) as u8 & 0xF,
                        resources: Vec::new(),
                        inbound: Queue::new(),
                        outbound: Queue::new(),
                    };
                    module.init();
                    session.items.push(module);
                }
                0x2415 => session.items.push(AC97::new(pci)),
                0x24C5 => session.items.push(AC97::new(pci)),
                0x2668 => {
                    let base = pci.read(0x10) as usize;
                    let mut module = box IntelHDA {
                        pci: pci,
                        base: base & 0xFFFFFFF0,
                        memory_mapped: base & 1 == 0,
                        irq: pci.read(0x3C) as u8 & 0xF,
                    };
                    module.init();
                    session.items.push(module);
                }
                _ => (),
            },
            _ => (),
        }
    }
}

/// Initialize PCI session
pub unsafe fn pci_init(session: &mut Session) {
    for bus in 0..256 {
        for slot in 0..32 {
            for func in 0..8 {
                let mut pci = PCIConfig::new(bus as u8, slot as u8, func as u8);
                let id = pci.read(0);

                if (id & 0xFFFF) != 0xFFFF {
                    let class_id = pci.read(8);

                    d(" * PCI ");
                    dd(bus);
                    d(", ");
                    dd(slot);
                    d(", ");
                    dd(func);
                    d(": ID ");
                    dh(id as usize);
                    d(" CL ");
                    dh(class_id as usize);

                    for i in 0..6 {
                        let bar = pci.read(i * 4 + 0x10);
                        if bar > 0 {
                            d(" BAR");
                            dd(i as usize);
                            d(": ");
                            dh(bar as usize);

                            pci.write(i * 4 + 0x10, 0xFFFFFFFF);
                            let size = (0xFFFFFFFF - (pci.read(i * 4 + 0x10) & 0xFFFFFFF0)) + 1;
                            pci.write(i * 4 + 0x10, bar);

                            if size > 0 {
                                d(" ");
                                dd(size as usize);
                            }
                        }
                    }

                    dl();

                    pci_device(session,
                               pci,
                               (class_id >> 24) & 0xFF,
                               (class_id >> 16) & 0xFF,
                               (class_id >> 8) & 0xFF,
                               id & 0xFFFF,
                               (id >> 16) & 0xFFFF);
                }
            }
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>added chap5<commit_after>fn power(x:i32) -> i32 {
	x+10
}

fn five_times<F:Fn(i32)->i32>(f:F,x:i32) -> i32 {
	f(f(f(f(x))))
}

fn main() {

	let num = 10;
	// using a higher order function here
	println!("{:?}",five_times(power,num));
	// or we can use a closure here to replace power function
	println!("{:?}",five_times(|n|n+10,num));
}<|endoftext|>


<commit_before><commit_msg>Quick self checks.<commit_after><|endoftext|>


<commit_before><commit_msg>Use "if let" if matching on a single pattern<commit_after><|endoftext|>


<commit_before><commit_msg>Adding new tests<commit_after>extern crate serde;

#[macro_use]
extern crate serde_jsonrc;

use serde_jsonrc::{Value, Deserializer, Error};
use serde_jsonrc::de::SliceRead;
use serde::de::Deserialize;

fn from_slice_with_unicode_substitution(s: &[u8]) -> Result<Value, Error> {
    let mut de = Deserializer::new(SliceRead::new(s, true));
    Deserialize::deserialize(&mut de)
}

#[test]
fn test_invalid_characters() {
    let prefix = r#" { "key": "value"#;
    let suffix = r#"" }"#;
    let mut s: Vec<u8> = vec![];
    s.extend(prefix.as_bytes());
    s.extend(&[0xed, 0xa0, 0x80]);
    s.extend(suffix.as_bytes());
    let value = from_slice_with_unicode_substitution(&s).unwrap();
    assert_eq!(value, json!({"key": "value\u{fffd}\u{fffd}\u{fffd}"}));
}

#[test]
fn test_invalid_utf16_escape_sequence() {
    let s = r#"
    {
        "key": "value\ud800"
    }"#.as_bytes();
    let value: Value = from_slice_with_unicode_substitution(&s).unwrap();
    assert_eq!(value, json!({"key": "value\u{fffd}"}));
}
<|endoftext|>


<commit_before><commit_msg>Start of rust. I think I'm going to go through tomfoolery to remove my need for doing my own buffer there. The interface doesn't have a one byte write, but that's really what I want to do here. Buffering is not my concern here.<commit_after>use std::fs::File;
use std::io::prelude::*;

fn emit_greyscale(scale: i32) {
    let size: usize = 2*(scale as usize) + 1;
    let mut output = File::create("test.pgm").unwrap();
    // So apparently the size of arrays in rust have to be a compile time
    // constant at the moment. Hardcode the value because whatever.
    let mut buf: [u8; 301] = [0; 301];
    write!(output, "P5 {} {} 255\n", size, size).unwrap();
    for xi in -scale .. (scale + 1) {
        for yi in -scale .. (scale + 1) {
            let x = xi as f32 / scale as f32;
            let y = yi as f32 / scale as f32;
            let intensity = (127.5 + 127.5*(x + y)/2.0) as u8;
            if xi == 0 {
                println!("Writing index {}", yi + scale);
            }
            buf[(yi + scale) as usize] = intensity;
        }
        output.write(&buf).unwrap();
    }
}
fn main() {
    emit_greyscale(150);
}
<|endoftext|>


<commit_before><commit_msg>Fix broken pipe panics<commit_after><|endoftext|>


<commit_before><commit_msg>Update as_you_type_formatter.rs<commit_after><|endoftext|>


<commit_before><commit_msg>added fold example<commit_after>extern crate kinder;

use kinder::lift::{Foldable, Monoid, SemiGroup};

fn sum_foldable<B : SemiGroup<A=B> + Monoid<A=B>, T: Foldable<A=B>>(xs: &T) -> B
{
    xs.foldr(B::id(), |x, y| x.add(y))
}

fn main() {
    let ints: Vec<i32> = vec!(1,2,3);
    let floats = vec!(1.0, 2.0, 3.0);
    let strings = vec!(String::from("Hello"), String::from(", "), String::from("World!"));

    println!("{}", sum_foldable(&ints)); //should print 6
    println!("{}", sum_foldable(&floats)); //should print 6.0
    println!("{}", sum_foldable(&strings)); //should print Hello, World!
}
<|endoftext|>


<commit_before><commit_msg>new range notation<commit_after><|endoftext|>


<commit_before><commit_msg>Add benchmark<commit_after>#![feature(test)]

extern crate test;
use test::Bencher;

extern crate resize;
extern crate png;

use std::fs::File;
use std::path::PathBuf;
use resize::Pixel::Gray8;
use resize::Type::Triangle;

fn get_image() -> (png::OutputInfo, Vec<u8>) {
    let root: PathBuf = env!("CARGO_MANIFEST_DIR").into();
    let decoder = png::Decoder::new(File::open(root.join("examples/tiger.png")).unwrap());
    let (info, mut reader) = decoder.read_info().unwrap();
    let mut src = vec![0;info.buffer_size()];
    reader.next_frame(&mut src).unwrap();
    (info, src)
}

#[bench]
fn precomputed_large(b: &mut Bencher) {
    let (info, src) = get_image();
    let (w1, h1) = (info.width as usize, info.height as usize);
    let (w2, h2) = (1600,1200);
    let mut dst = vec![0;w2*h2];

    let mut r = resize::new(w1, h1, w2, h2, Gray8, Triangle);

    b.iter(|| r.resize(&src, &mut dst));
}

#[bench]
fn precomputed_small(b: &mut Bencher) {
    let (info, src) = get_image();
    let (w1, h1) = (info.width as usize, info.height as usize);
    let (w2, h2) = (100,100);
    let mut dst = vec![0;w2*h2];

    let mut r = resize::new(w1, h1, w2, h2, Gray8, Triangle);

    b.iter(|| r.resize(&src, &mut dst));
}

#[bench]
fn recomputed_small(b: &mut Bencher) {
    let (info, src) = get_image();
    let (w1, h1) = (info.width as usize, info.height as usize);
    let (w2, h2) = (100,100);
    let mut dst = vec![0;w2*h2];

    b.iter(|| resize::resize(w1, h1, w2, h2, Gray8, Triangle, &src, &mut dst));
}
<|endoftext|>


<commit_before>use redox::*;

// nvp implementation version
const NV_VERSION: i32 = 0;

// nvlist header
pub struct NvList {
    pub version: i32,
    pub nvflag:  u32, // persistent flags
    pub pairs: Vec<(String, NvValue)>,
}

impl NvList {
    pub fn new(nvflag: u32) -> NvList {
        NvList {
            version: NV_VERSION,
            nvflag: nvflag,
            pairs: Vec::new(),
        }
    }
}

enum DataType {
    Unknown = 0,
    Boolean,
    Byte,
    Int16,
    Uint16,
    Int32,
    Uint32,
    Int64,
    Uint64,
    String,
    ByteArray,
    Int16Array,
    Uint16Array,
    Int32Array,
    Uint32Array,
    Int64Array,
    Uint64Array,
    StringArray,
    HrTime,
    NvList,
    NvListArray,
    BooleanValue,
    Int8,
    Uint8,
    BooleanArray,
    Int8Array,
    Uint8Array,
}

pub enum NvValue {
    Unknown,
    Boolean,
    Byte(u8),
    Int16(i16),
    Uint16(u16),
    Int32(i32),
    Uint32(u32),
    Int64(i64),
    Uint64(u64),
    String(String),
    ByteArray(Vec<u8>),
    Int16Array(Vec<i16>),
    Uint16Array(Vec<u16>),
    Int32Array(Vec<i32>),
    Uint32Array(Vec<u32>),
    Int64Array(Vec<i64>),
    Uint64Array(Vec<u64>),
    StringArray(Vec<String>),
    HrTime,
    NvList(Box<NvList>),
    NvListArray(Vec<Box<NvList>>),
    BooleanValue(bool),
    Int8(i8),
    Uint8(u8),
    BooleanArray(Vec<bool>),
    Int8Array(Vec<i8>),
    Uint8Array(Vec<u8>),
}
<commit_msg>Use Self in NvPairs impl<commit_after>use redox::*;

// nvp implementation version
const NV_VERSION: i32 = 0;

// nvlist header
pub struct NvList {
    pub version: i32,
    pub nvflag:  u32, // persistent flags
    pub pairs: Vec<(String, NvValue)>,
}

impl NvList {
    pub fn new(nvflag: u32) -> Self {
        NvList {
            version: NV_VERSION,
            nvflag: nvflag,
            pairs: Vec::new(),
        }
    }
}

enum DataType {
    Unknown = 0,
    Boolean,
    Byte,
    Int16,
    Uint16,
    Int32,
    Uint32,
    Int64,
    Uint64,
    String,
    ByteArray,
    Int16Array,
    Uint16Array,
    Int32Array,
    Uint32Array,
    Int64Array,
    Uint64Array,
    StringArray,
    HrTime,
    NvList,
    NvListArray,
    BooleanValue,
    Int8,
    Uint8,
    BooleanArray,
    Int8Array,
    Uint8Array,
}

pub enum NvValue {
    Unknown,
    Boolean,
    Byte(u8),
    Int16(i16),
    Uint16(u16),
    Int32(i32),
    Uint32(u32),
    Int64(i64),
    Uint64(u64),
    String(String),
    ByteArray(Vec<u8>),
    Int16Array(Vec<i16>),
    Uint16Array(Vec<u16>),
    Int32Array(Vec<i32>),
    Uint32Array(Vec<u32>),
    Int64Array(Vec<i64>),
    Uint64Array(Vec<u64>),
    StringArray(Vec<String>),
    HrTime,
    NvList(Box<NvList>),
    NvListArray(Vec<Box<NvList>>),
    BooleanValue(bool),
    Int8(i8),
    Uint8(u8),
    BooleanArray(Vec<bool>),
    Int8Array(Vec<i8>),
    Uint8Array(Vec<u8>),
}
<|endoftext|>


<commit_before>// Copyright 2012-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.

//! Types which pin data to its location in memory
//!
//! see the [standard library module] for more information
//!
//! [standard library module]: ../../std/pin/index.html

#![unstable(feature = "pin", issue = "49150")]

use fmt;
use future::{Future, UnsafeFutureObj};
use marker::{Sized, Unpin, Unsize};
use task::{Context, Poll};
use ops::{Deref, DerefMut, CoerceUnsized};

/// A pinned reference.
///
/// This type is similar to a mutable reference, except that it pins its value,
/// which prevents it from moving out of the reference, unless it implements [`Unpin`].
///
/// See the [`pin` module] documentation for furthur explanation on pinning.
///
/// [`Unpin`]: ../marker/trait.Unpin.html
/// [`pin` module]: ../../alloc/pin/index.html
#[unstable(feature = "pin", issue = "49150")]
#[fundamental]
pub struct PinMut<'a, T: ?Sized + 'a> {
    inner: &'a mut T,
}

#[unstable(feature = "pin", issue = "49150")]
impl<'a, T: ?Sized + Unpin> PinMut<'a, T> {
    /// Construct a new `PinMut` around a reference to some data of a type that
    /// implements `Unpin`.
    #[unstable(feature = "pin", issue = "49150")]
    pub fn new(reference: &'a mut T) -> PinMut<'a, T> {
        PinMut { inner: reference }
    }

    /// Get a mutable reference to the data inside of this `PinMut`.
    #[unstable(feature = "pin", issue = "49150")]
    pub fn get_mut(this: PinMut<'a, T>) -> &'a mut T {
        this.inner
    }
}

#[unstable(feature = "pin", issue = "49150")]
impl<'a, T: ?Sized> PinMut<'a, T> {
    /// Construct a new `PinMut` around a reference to some data of a type that
    /// may or may not implement `Unpin`.
    ///
    /// This constructor is unsafe because we do not know what will happen with
    /// that data after the lifetime of the reference ends. If you cannot guarantee that the
    /// data will never move again, calling this constructor is invalid.
    #[unstable(feature = "pin", issue = "49150")]
    pub unsafe fn new_unchecked(reference: &'a mut T) -> PinMut<'a, T> {
        PinMut { inner: reference }
    }

    /// Reborrow a `PinMut` for a shorter lifetime.
    ///
    /// For example, `PinMut::get_mut(x.reborrow())` (unsafely) returns a
    /// short-lived mutable reference reborrowing from `x`.
    #[unstable(feature = "pin", issue = "49150")]
    pub fn reborrow<'b>(&'b mut self) -> PinMut<'b, T> {
        PinMut { inner: self.inner }
    }

    /// Get a mutable reference to the data inside of this `PinMut`.
    ///
    /// This function is unsafe. You must guarantee that you will never move
    /// the data out of the mutable reference you receive when you call this
    /// function.
    #[unstable(feature = "pin", issue = "49150")]
    pub unsafe fn get_mut_unchecked(this: PinMut<'a, T>) -> &'a mut T {
        this.inner
    }

    /// Construct a new pin by mapping the interior value.
    ///
    /// For example, if you  wanted to get a `PinMut` of a field of something,
    /// you could use this to get access to that field in one line of code.
    ///
    /// This function is unsafe. You must guarantee that the data you return
    /// will not move so long as the argument value does not move (for example,
    /// because it is one of the fields of that value), and also that you do
    /// not move out of the argument you receive to the interior function.
    #[unstable(feature = "pin", issue = "49150")]
    pub unsafe fn map_unchecked<U, F>(this: PinMut<'a, T>, f: F) -> PinMut<'a, U> where
        F: FnOnce(&mut T) -> &mut U
    {
        PinMut { inner: f(this.inner) }
    }

    /// Assign a new value to the memory behind the pinned reference.
    #[unstable(feature = "pin", issue = "49150")]
    pub fn set(this: PinMut<'a, T>, value: T)
        where T: Sized,
    {
        *this.inner = value;
    }
}

#[unstable(feature = "pin", issue = "49150")]
impl<'a, T: ?Sized> Deref for PinMut<'a, T> {
    type Target = T;

    fn deref(&self) -> &T {
        &*self.inner
    }
}

#[unstable(feature = "pin", issue = "49150")]
impl<'a, T: ?Sized + Unpin> DerefMut for PinMut<'a, T> {
    fn deref_mut(&mut self) -> &mut T {
        self.inner
    }
}

#[unstable(feature = "pin", issue = "49150")]
impl<'a, T: fmt::Debug + ?Sized> fmt::Debug for PinMut<'a, T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Debug::fmt(&**self, f)
    }
}

#[unstable(feature = "pin", issue = "49150")]
impl<'a, T: fmt::Display + ?Sized> fmt::Display for PinMut<'a, T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Display::fmt(&**self, f)
    }
}

#[unstable(feature = "pin", issue = "49150")]
impl<'a, T: ?Sized> fmt::Pointer for PinMut<'a, T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Pointer::fmt(&(&*self.inner as *const T), f)
    }
}

#[unstable(feature = "pin", issue = "49150")]
impl<'a, T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<PinMut<'a, U>> for PinMut<'a, T> {}

#[unstable(feature = "pin", issue = "49150")]
impl<'a, T: ?Sized> Unpin for PinMut<'a, T> {}

#[unstable(feature = "futures_api", issue = "50547")]
unsafe impl<'a, T, F> UnsafeFutureObj<'a, T> for PinMut<'a, F>
    where F: Future<Output = T> + 'a
{
    fn into_raw(self) -> *mut () {
        unsafe { PinMut::get_mut_unchecked(self) as *mut F as *mut () }
    }

    unsafe fn poll(ptr: *mut (), cx: &mut Context) -> Poll<T> {
        PinMut::new_unchecked(&mut *(ptr as *mut F)).poll(cx)
    }

    unsafe fn drop(_ptr: *mut ()) {}
}
<commit_msg>fix broken link to Unpin due to reexport<commit_after>// Copyright 2012-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.

//! Types which pin data to its location in memory
//!
//! see the [standard library module] for more information
//!
//! [standard library module]: ../../std/pin/index.html

#![unstable(feature = "pin", issue = "49150")]

use fmt;
use future::{Future, UnsafeFutureObj};
use marker::{Sized, Unpin, Unsize};
use task::{Context, Poll};
use ops::{Deref, DerefMut, CoerceUnsized};

/// A pinned reference.
///
/// This type is similar to a mutable reference, except that it pins its value,
/// which prevents it from moving out of the reference, unless it implements [`Unpin`].
///
/// See the [`pin` module] documentation for furthur explanation on pinning.
///
/// [`Unpin`]: ../../core/marker/trait.Unpin.html
/// [`pin` module]: ../../alloc/pin/index.html
#[unstable(feature = "pin", issue = "49150")]
#[fundamental]
pub struct PinMut<'a, T: ?Sized + 'a> {
    inner: &'a mut T,
}

#[unstable(feature = "pin", issue = "49150")]
impl<'a, T: ?Sized + Unpin> PinMut<'a, T> {
    /// Construct a new `PinMut` around a reference to some data of a type that
    /// implements `Unpin`.
    #[unstable(feature = "pin", issue = "49150")]
    pub fn new(reference: &'a mut T) -> PinMut<'a, T> {
        PinMut { inner: reference }
    }

    /// Get a mutable reference to the data inside of this `PinMut`.
    #[unstable(feature = "pin", issue = "49150")]
    pub fn get_mut(this: PinMut<'a, T>) -> &'a mut T {
        this.inner
    }
}

#[unstable(feature = "pin", issue = "49150")]
impl<'a, T: ?Sized> PinMut<'a, T> {
    /// Construct a new `PinMut` around a reference to some data of a type that
    /// may or may not implement `Unpin`.
    ///
    /// This constructor is unsafe because we do not know what will happen with
    /// that data after the lifetime of the reference ends. If you cannot guarantee that the
    /// data will never move again, calling this constructor is invalid.
    #[unstable(feature = "pin", issue = "49150")]
    pub unsafe fn new_unchecked(reference: &'a mut T) -> PinMut<'a, T> {
        PinMut { inner: reference }
    }

    /// Reborrow a `PinMut` for a shorter lifetime.
    ///
    /// For example, `PinMut::get_mut(x.reborrow())` (unsafely) returns a
    /// short-lived mutable reference reborrowing from `x`.
    #[unstable(feature = "pin", issue = "49150")]
    pub fn reborrow<'b>(&'b mut self) -> PinMut<'b, T> {
        PinMut { inner: self.inner }
    }

    /// Get a mutable reference to the data inside of this `PinMut`.
    ///
    /// This function is unsafe. You must guarantee that you will never move
    /// the data out of the mutable reference you receive when you call this
    /// function.
    #[unstable(feature = "pin", issue = "49150")]
    pub unsafe fn get_mut_unchecked(this: PinMut<'a, T>) -> &'a mut T {
        this.inner
    }

    /// Construct a new pin by mapping the interior value.
    ///
    /// For example, if you  wanted to get a `PinMut` of a field of something,
    /// you could use this to get access to that field in one line of code.
    ///
    /// This function is unsafe. You must guarantee that the data you return
    /// will not move so long as the argument value does not move (for example,
    /// because it is one of the fields of that value), and also that you do
    /// not move out of the argument you receive to the interior function.
    #[unstable(feature = "pin", issue = "49150")]
    pub unsafe fn map_unchecked<U, F>(this: PinMut<'a, T>, f: F) -> PinMut<'a, U> where
        F: FnOnce(&mut T) -> &mut U
    {
        PinMut { inner: f(this.inner) }
    }

    /// Assign a new value to the memory behind the pinned reference.
    #[unstable(feature = "pin", issue = "49150")]
    pub fn set(this: PinMut<'a, T>, value: T)
        where T: Sized,
    {
        *this.inner = value;
    }
}

#[unstable(feature = "pin", issue = "49150")]
impl<'a, T: ?Sized> Deref for PinMut<'a, T> {
    type Target = T;

    fn deref(&self) -> &T {
        &*self.inner
    }
}

#[unstable(feature = "pin", issue = "49150")]
impl<'a, T: ?Sized + Unpin> DerefMut for PinMut<'a, T> {
    fn deref_mut(&mut self) -> &mut T {
        self.inner
    }
}

#[unstable(feature = "pin", issue = "49150")]
impl<'a, T: fmt::Debug + ?Sized> fmt::Debug for PinMut<'a, T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Debug::fmt(&**self, f)
    }
}

#[unstable(feature = "pin", issue = "49150")]
impl<'a, T: fmt::Display + ?Sized> fmt::Display for PinMut<'a, T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Display::fmt(&**self, f)
    }
}

#[unstable(feature = "pin", issue = "49150")]
impl<'a, T: ?Sized> fmt::Pointer for PinMut<'a, T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Pointer::fmt(&(&*self.inner as *const T), f)
    }
}

#[unstable(feature = "pin", issue = "49150")]
impl<'a, T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<PinMut<'a, U>> for PinMut<'a, T> {}

#[unstable(feature = "pin", issue = "49150")]
impl<'a, T: ?Sized> Unpin for PinMut<'a, T> {}

#[unstable(feature = "futures_api", issue = "50547")]
unsafe impl<'a, T, F> UnsafeFutureObj<'a, T> for PinMut<'a, F>
    where F: Future<Output = T> + 'a
{
    fn into_raw(self) -> *mut () {
        unsafe { PinMut::get_mut_unchecked(self) as *mut F as *mut () }
    }

    unsafe fn poll(ptr: *mut (), cx: &mut Context) -> Poll<T> {
        PinMut::new_unchecked(&mut *(ptr as *mut F)).poll(cx)
    }

    unsafe fn drop(_ptr: *mut ()) {}
}
<|endoftext|>


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

#![allow(missing_docs)]
#![unstable(feature = "raw", issue = "27751")]

//! Contains struct definitions for the layout of compiler built-in types.
//!
//! They can be used as targets of transmutes in unsafe code for manipulating
//! the raw representations directly.
//!
//! Their definition should always match the ABI defined in `rustc::back::abi`.

/// The representation of a trait object like `&SomeTrait`.
///
/// This struct has the same layout as types like `&SomeTrait` and
/// `Box<AnotherTrait>`. The [Trait Objects chapter of the
/// Book][moreinfo] contains more details about the precise nature of
/// these internals.
///
/// [moreinfo]: ../../book/trait-objects.html#representation
///
/// `TraitObject` is guaranteed to match layouts, but it is not the
/// type of trait objects (e.g. the fields are not directly accessible
/// on a `&SomeTrait`) nor does it control that layout (changing the
/// definition will not change the layout of a `&SomeTrait`). It is
/// only designed to be used by unsafe code that needs to manipulate
/// the low-level details.
///
/// There is no `Repr` implementation for `TraitObject` because there
/// is no way to refer to all trait objects generically, so the only
/// way to create values of this type is with functions like
/// `std::mem::transmute`. Similarly, the only way to create a true
/// trait object from a `TraitObject` value is with `transmute`.
///
/// Synthesizing a trait object with mismatched types—one where the
/// vtable does not correspond to the type of the value to which the
/// data pointer points—is highly likely to lead to undefined
/// behavior.
///
/// # Examples
///
/// ```
/// #![feature(raw)]
///
/// use std::mem;
/// use std::raw;
///
/// // an example trait
/// trait Foo {
///     fn bar(&self) -> i32;
/// }
/// impl Foo for i32 {
///     fn bar(&self) -> i32 {
///          *self + 1
///     }
/// }
///
/// let value: i32 = 123;
///
/// // let the compiler make a trait object
/// let object: &Foo = &value;
///
/// // look at the raw representation
/// let raw_object: raw::TraitObject = unsafe { mem::transmute(object) };
///
/// // the data pointer is the address of `value`
/// assert_eq!(raw_object.data as *const i32, &value as *const _);
///
///
/// let other_value: i32 = 456;
///
/// // construct a new object, pointing to a different `i32`, being
/// // careful to use the `i32` vtable from `object`
/// let synthesized: &Foo = unsafe {
///      mem::transmute(raw::TraitObject {
///          data: &other_value as *const _ as *mut (),
///          vtable: raw_object.vtable
///      })
/// };
///
/// // it should work just like we constructed a trait object out of
/// // `other_value` directly
/// assert_eq!(synthesized.bar(), 457);
/// ```
#[repr(C)]
#[derive(Copy, Clone)]
#[allow(missing_debug_implementations)]
pub struct TraitObject {
    pub data: *mut (),
    pub vtable: *mut (),
}
<commit_msg>Rollup merge of #35281 - apasel422:repr, r=GuillaumeGomez<commit_after>// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

#![allow(missing_docs)]
#![unstable(feature = "raw", issue = "27751")]

//! Contains struct definitions for the layout of compiler built-in types.
//!
//! They can be used as targets of transmutes in unsafe code for manipulating
//! the raw representations directly.
//!
//! Their definition should always match the ABI defined in `rustc::back::abi`.

/// The representation of a trait object like `&SomeTrait`.
///
/// This struct has the same layout as types like `&SomeTrait` and
/// `Box<AnotherTrait>`. The [Trait Objects chapter of the
/// Book][moreinfo] contains more details about the precise nature of
/// these internals.
///
/// [moreinfo]: ../../book/trait-objects.html#representation
///
/// `TraitObject` is guaranteed to match layouts, but it is not the
/// type of trait objects (e.g. the fields are not directly accessible
/// on a `&SomeTrait`) nor does it control that layout (changing the
/// definition will not change the layout of a `&SomeTrait`). It is
/// only designed to be used by unsafe code that needs to manipulate
/// the low-level details.
///
/// There is no way to refer to all trait objects generically, so the only
/// way to create values of this type is with functions like
/// [`std::mem::transmute`][transmute]. Similarly, the only way to create a true
/// trait object from a `TraitObject` value is with `transmute`.
///
/// [transmute]: ../intrinsics/fn.transmute.html
///
/// Synthesizing a trait object with mismatched types—one where the
/// vtable does not correspond to the type of the value to which the
/// data pointer points—is highly likely to lead to undefined
/// behavior.
///
/// # Examples
///
/// ```
/// #![feature(raw)]
///
/// use std::{mem, raw};
///
/// // an example trait
/// trait Foo {
///     fn bar(&self) -> i32;
/// }
///
/// impl Foo for i32 {
///     fn bar(&self) -> i32 {
///          *self + 1
///     }
/// }
///
/// let value: i32 = 123;
///
/// // let the compiler make a trait object
/// let object: &Foo = &value;
///
/// // look at the raw representation
/// let raw_object: raw::TraitObject = unsafe { mem::transmute(object) };
///
/// // the data pointer is the address of `value`
/// assert_eq!(raw_object.data as *const i32, &value as *const _);
///
/// let other_value: i32 = 456;
///
/// // construct a new object, pointing to a different `i32`, being
/// // careful to use the `i32` vtable from `object`
/// let synthesized: &Foo = unsafe {
///      mem::transmute(raw::TraitObject {
///          data: &other_value as *const _ as *mut (),
///          vtable: raw_object.vtable,
///      })
/// };
///
/// // it should work just as if we had constructed a trait object out of
/// // `other_value` directly
/// assert_eq!(synthesized.bar(), 457);
/// ```
#[repr(C)]
#[derive(Copy, Clone)]
#[allow(missing_debug_implementations)]
pub struct TraitObject {
    pub data: *mut (),
    pub vtable: *mut (),
}
<|endoftext|>


<commit_before><commit_msg>:art: Make ignore tasks without deadline<commit_after><|endoftext|>


<commit_before><commit_msg>Fix the max-frames triggered calculation so that it only renders the number of frames you ask for<commit_after><|endoftext|>


<commit_before><commit_msg>Initial commit for version.rs<commit_after><|endoftext|>


<commit_before><commit_msg>Fix descriptor set layout and descriptor set construction for shared uniform buffers<commit_after><|endoftext|>


<commit_before><commit_msg>Block type must be sent as LittleEndian.<commit_after><|endoftext|>


<commit_before><commit_msg>refactor: replace checked vector access followed by unwrap with indexing<commit_after><|endoftext|>


<commit_before>mod xdg_v6;
mod xdg;

pub use self::xdg_v6::*;
pub use self::xdg::*;

use wlroots::{Area, HandleResult, SurfaceHandle, XdgV6ShellSurfaceHandle,
              XdgShellSurfaceHandle};

#[derive(Debug, Clone, Eq, PartialEq)]
pub enum Shell {
    XdgV6(XdgV6ShellSurfaceHandle),
    Xdg(XdgShellSurfaceHandle)
}

impl Shell {
    /// Get a wlr surface from the shell.
    pub fn surface(&self) -> SurfaceHandle {
        match self.clone() {
            Shell::XdgV6(shell) => {
                shell.run(|shell| shell.surface())
                     .expect("An xdg v6 client did not provide us a surface")
            },
            Shell::Xdg(mut shell) => {
                shell.run(|shell| shell.surface())
                    .expect("An xdg client did not provide us a surface")
            }
        }
    }

    /// Get the geometry of a shell.
    pub fn geometry(&mut self) -> HandleResult<Area> {
        match *self {
            Shell::XdgV6(ref mut shell) => shell.run(|shell| shell.geometry()),
            Shell::Xdg(ref mut shell) => shell.run(|shell| shell.geometry())
        }
    }
}

impl Into<Shell> for XdgV6ShellSurfaceHandle {
    fn into(self) -> Shell {
        Shell::XdgV6(self)
    }
}

impl Into<Shell> for XdgShellSurfaceHandle {
    fn into(self) -> Shell {
        Shell::Xdg(self)
    }
}
<commit_msg>Unused mut<commit_after>mod xdg_v6;
mod xdg;

pub use self::xdg_v6::*;
pub use self::xdg::*;

use wlroots::{Area, HandleResult, SurfaceHandle, XdgV6ShellSurfaceHandle,
              XdgShellSurfaceHandle};

#[derive(Debug, Clone, Eq, PartialEq)]
pub enum Shell {
    XdgV6(XdgV6ShellSurfaceHandle),
    Xdg(XdgShellSurfaceHandle)
}

impl Shell {
    /// Get a wlr surface from the shell.
    pub fn surface(&self) -> SurfaceHandle {
        match self.clone() {
            Shell::XdgV6(shell) => {
                shell.run(|shell| shell.surface())
                     .expect("An xdg v6 client did not provide us a surface")
            },
            Shell::Xdg(shell) => {
                shell.run(|shell| shell.surface())
                    .expect("An xdg client did not provide us a surface")
            }
        }
    }

    /// Get the geometry of a shell.
    pub fn geometry(&mut self) -> HandleResult<Area> {
        match *self {
            Shell::XdgV6(ref mut shell) => shell.run(|shell| shell.geometry()),
            Shell::Xdg(ref mut shell) => shell.run(|shell| shell.geometry())
        }
    }
}

impl Into<Shell> for XdgV6ShellSurfaceHandle {
    fn into(self) -> Shell {
        Shell::XdgV6(self)
    }
}

impl Into<Shell> for XdgShellSurfaceHandle {
    fn into(self) -> Shell {
        Shell::Xdg(self)
    }
}
<|endoftext|>


<commit_before><commit_msg>Add problem #45<commit_after>fn triangle(i: uint) -> uint {
    let n = i + 1;
    return n * (n + 1) / 2;
}

fn pentagonal(i: uint) -> uint {
    let n = i + 1;
    return n * (3 * n - 1) / 2;
}

fn hexagonal(i: uint) -> uint {
    let n = i + 1;
    return n * (2 * n - 1);
}

fn main() {
    let mut n = 40755 + 1;
    let mut t_i = 0;
    let mut p_i = 0;
    let mut h_i = 0;

    loop {
        let mut t = triangle(t_i);
        while t < n {
            t_i += 1;
            t = triangle(t_i);
        }
        if t > n { n = t; }

        let mut p = pentagonal(p_i);
        while p < n {
            p_i += 1;
            p = pentagonal(p_i);
        }
        if p > n { n = p; loop; }

        let mut h = hexagonal(h_i);
        while h < n {
            h_i += 1;
            h = hexagonal(h_i);
        }
        if h > n { n = h; loop; }

        break;
    }

    io::println(fmt!("T[%u] = P[%u] = H[%u] = %u", t_i, p_i, h_i, triangle(t_i)));
    io::println(fmt!("answer: %u", triangle(t_i)));
}
<|endoftext|>


<commit_before><commit_msg>Add problem #28<commit_after>// 43 44 45 46 47 48 49
// 42 21 22 23 24 25 26
// 41 20  7  8  9 10 27
// 40 19  6  1  2 11 28
// 39 18  5  4  3 12 29
// 38 17 16 15 14 13 30
// 37 36 35 34 33 32 31

// n = square size (1 by 1 => n = 1, 3 by 3 => n = 9)
// Upper right => 1, 9, 25, 49
//             => ur[n] := n^2
// Upper left  => 1, 7, 21, 43 = 1 - 0, 9 - 2, 25 - 4, 49 - 6
//             => ul[n] := ur[n] - (n - 1) = n^2 - n + 1
// Lower left  => 1, 5, 17, 37 = 1 - 0, 7 - 2, 21 - 4, 43 - 6
//             => ll[n] := ul[n] - (n - 1) = n^2 - 2n + 2
// Lower right => 1, 3, 13, 31 = 1 - 0, 5 - 2, 17 - 4, 37 - 6
//             => lr[n] := ll[n] - (n - 1) = n^2 - 3n + 3

// sum[n] = ur[n] + ul[n] + ll[n] + lr[n] = 4n^2 - 6n + 6

// n = 2k - 1
// sum[n] = 16k^2 - 28k + 16

// N := (n + 1) / 2
// ans[n] = \sum_{k=1}^{N} sum[k] - 3
//        = 1/6 (4n^3 + 3n^2 + 8n - 9)
fn sum(n: uint) -> uint {
    (4 * n*n*n + 3 * n*n + 8 * n - 9) / 6
}

fn main() {
    io::println(fmt!("%u", sum(1001)));
}
<|endoftext|>


<commit_before><commit_msg>Use an empty enum for Void; fix #1 thanks to @reem<commit_after><|endoftext|>


<commit_before>// The Computer Language Benchmarks Game
// http://benchmarksgame.alioth.debian.org/
//
// contributed by the Rust Project Developers

// Copyright (c) 2013-2014 The Rust Project Developers
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// - Redistributions of source code must retain the above copyright
//   notice, this list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright
//   notice, this list of conditions and the following disclaimer in
//   the documentation and/or other materials provided with the
//   distribution.
//
// - Neither the name of "The Computer Language Benchmarks Game" nor
//   the name of "The Computer Language Shootout Benchmarks" nor the
//   names of its contributors may be used to endorse or promote
//   products derived from this software without specific prior
//   written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
// OF THE POSSIBILITY OF SUCH DAMAGE.

#![feature(slicing_syntax, asm, if_let, tuple_indexing)]

extern crate libc;

use std::io::stdio::{stdin_raw, stdout_raw};
use std::sync::{Future};
use std::num::{div_rem};
use std::ptr::{copy_memory};
use std::io::{IoResult, EndOfFile};
use std::slice::raw::{mut_buf_as_slice};

use shared_memory::{SharedMemory};

mod tables {
    use std::sync::{Once, ONCE_INIT};

    /// Lookup tables.
    static mut CPL16: [u16, ..1 << 16] = [0, ..1 << 16];
    static mut CPL8:  [u8,  ..1 << 8]  = [0, ..1 << 8];

    /// Generates the tables.
    pub fn get() -> Tables {
        /// To make sure we initialize the tables only once.
        static INIT: Once = ONCE_INIT;
        INIT.doit(|| {
            unsafe {
                for i in range(0, 1 << 8) {
                    CPL8[i] = match i as u8 {
                        b'A' | b'a' => b'T',
                        b'C' | b'c' => b'G',
                        b'G' | b'g' => b'C',
                        b'T' | b't' => b'A',
                        b'U' | b'u' => b'A',
                        b'M' | b'm' => b'K',
                        b'R' | b'r' => b'Y',
                        b'W' | b'w' => b'W',
                        b'S' | b's' => b'S',
                        b'Y' | b'y' => b'R',
                        b'K' | b'k' => b'M',
                        b'V' | b'v' => b'B',
                        b'H' | b'h' => b'D',
                        b'D' | b'd' => b'H',
                        b'B' | b'b' => b'V',
                        b'N' | b'n' => b'N',
                        i => i,
                    };
                }

                for (i, v) in CPL16.iter_mut().enumerate() {
                    *v = *CPL8.unsafe_get(i & 255) as u16 << 8 |
                         *CPL8.unsafe_get(i >> 8)  as u16;
                }
            }
        });
        Tables { _dummy: () }
    }

    /// Accessor for the static arrays.
    ///
    /// To make sure that the tables can't be accessed without having been initialized.
    pub struct Tables {
        _dummy: ()
    }

    impl Tables {
        /// Retreives the complement for `i`.
        pub fn cpl8(self, i: u8) -> u8 {
            // Not really unsafe.
            unsafe { CPL8[i as uint] }
        }

        /// Retreives the complement for `i`.
        pub fn cpl16(self, i: u16) -> u16 {
            unsafe { CPL16[i as uint] }
        }
    }
}

mod shared_memory {
    use std::sync::{Arc};
    use std::mem::{transmute};
    use std::raw::{Slice};

    /// Structure for sharing disjoint parts of a vector mutably across tasks.
    pub struct SharedMemory {
        ptr: Arc<Vec<u8>>,
        start: uint,
        len: uint,
    }

    impl SharedMemory {
        pub fn new(ptr: Vec<u8>) -> SharedMemory {
            let len = ptr.len();
            SharedMemory {
                ptr: Arc::new(ptr),
                start: 0,
                len: len,
            }
        }

        pub fn as_mut_slice(&mut self) -> &mut [u8] {
            unsafe {
                transmute(Slice {
                    data: self.ptr.as_ptr().offset(self.start as int) as *const u8,
                    len: self.len,
                })
            }
        }

        pub fn len(&self) -> uint {
            self.len
        }

        pub fn split_at(self, mid: uint) -> (SharedMemory, SharedMemory) {
            assert!(mid <= self.len);
            let left = SharedMemory {
                ptr: self.ptr.clone(),
                start: self.start,
                len: mid,
            };
            let right = SharedMemory {
                ptr: self.ptr,
                start: self.start + mid,
                len: self.len - mid,
            };
            (left, right)
        }

        /// Resets the object so that it covers the whole range of the contained vector.
        ///
        /// You must not call this method if `self` is not the only reference to the
        /// shared memory.
        ///
        /// FIXME: If `Arc` had a method to check if the reference is unique, then we
        /// wouldn't need the `unsafe` here.
        ///
        /// FIXME: If `Arc` had a method to unwrap the contained value, then we could
        /// simply unwrap here.
        pub unsafe fn reset(self) -> SharedMemory {
            let len = self.ptr.len();
            SharedMemory {
                ptr: self.ptr,
                start: 0,
                len: len,
            }
        }
    }
}

/// Reads all remaining bytes from the stream.
fn read_to_end<R: Reader>(r: &mut R) -> IoResult<Vec<u8>> {
    const CHUNK: uint = 64 * 1024;

    let mut vec = Vec::with_capacity(1024 * 1024);
    loop {
        if vec.capacity() - vec.len() < CHUNK {
            let cap = vec.capacity();
            let mult = if cap < 256 * 1024 * 1024 {
                // FIXME (mahkoh): Temporary workaround for jemalloc on linux. Replace
                // this by 2x once the jemalloc preformance issue has been fixed.
                16
            } else {
                2
            };
            vec.reserve_exact(mult * cap);
        }
        unsafe {
            let ptr = vec.as_mut_ptr().offset(vec.len() as int);
            match mut_buf_as_slice(ptr, CHUNK, |s| r.read(s)) {
                Ok(n) => {
                    let len = vec.len();
                    vec.set_len(len + n);
                },
                Err(ref e) if e.kind == EndOfFile => break,
                Err(e) => return Err(e),
            }
        }
    }
    Ok(vec)
}

/// Finds the first position at which `b` occurs in `s`.
fn memchr(h: &[u8], n: u8) -> Option<uint> {
    use libc::{c_void, c_int, size_t};
    extern {
        fn memchr(h: *const c_void, n: c_int, s: size_t) -> *mut c_void;
    }
    let res = unsafe {
        memchr(h.as_ptr() as *const c_void, n as c_int, h.len() as size_t)
    };
    if res.is_null() {
        None
    } else {
        Some(res as uint - h.as_ptr() as uint)
    }
}

/// Length of a normal line without the terminating \n.
const LINE_LEN: uint = 60;

/// Compute the reverse complement.
fn reverse_complement(mut view: SharedMemory, tables: tables::Tables) {
    // Drop the last newline
    let seq = view.as_mut_slice().init_mut();
    let len = seq.len();
    let off = LINE_LEN - len % (LINE_LEN + 1);
    let mut i = LINE_LEN;
    while i < len {
        unsafe {
            copy_memory(seq.as_mut_ptr().offset((i - off + 1) as int),
                        seq.as_ptr().offset((i - off) as int), off);
            *seq.unsafe_mut(i - off) = b'\n';
        }
        i += LINE_LEN + 1;
    }

    let (div, rem) = div_rem(len, 4);
    unsafe {
        let mut left = seq.as_mut_ptr() as *mut u16;
        // This is slow if len % 2 != 0 but still faster than bytewise operations.
        let mut right = seq.as_mut_ptr().offset(len as int - 2) as *mut u16;
        let end = left.offset(div as int);
        while left != end {
            let tmp = tables.cpl16(*left);
            *left = tables.cpl16(*right);
            *right = tmp;
            left = left.offset(1);
            right = right.offset(-1);
        }

        let end = end as *mut u8;
        match rem {
            1 => *end = tables.cpl8(*end),
            2 => {
                let tmp = tables.cpl8(*end);
                *end = tables.cpl8(*end.offset(1));
                *end.offset(1) = tmp;
            },
            3 => {
                *end.offset(1) = tables.cpl8(*end.offset(1));
                let tmp = tables.cpl8(*end);
                *end = tables.cpl8(*end.offset(2));
                *end.offset(2) = tmp;
            },
            _ => { },
        }
    }
}

fn main() {
    let mut data = SharedMemory::new(read_to_end(&mut stdin_raw()).unwrap());
    let tables = tables::get();

    let mut futures = vec!();
    loop {
        let (_, mut tmp_data) = match memchr(data.as_mut_slice(), b'\n') {
            Some(i) => data.split_at(i + 1),
            _ => break,
        };
        let (view, tmp_data) = match memchr(tmp_data.as_mut_slice(), b'>') {
            Some(i) => tmp_data.split_at(i),
            None => {
                let len = tmp_data.len();
                tmp_data.split_at(len)
            },
        };
        futures.push(Future::spawn(proc() reverse_complement(view, tables)));
        data = tmp_data;
    }

    for f in futures.iter_mut() {
        f.get();
    }

    // Not actually unsafe. If Arc had a way to check uniqueness then we could do that in
    // `reset` and it would tell us that, yes, it is unique at this point.
    data = unsafe { data.reset() };

    stdout_raw().write(data.as_mut_slice()).unwrap();
}
<commit_msg>ignore-android<commit_after>// The Computer Language Benchmarks Game
// http://benchmarksgame.alioth.debian.org/
//
// contributed by the Rust Project Developers

// Copyright (c) 2013-2014 The Rust Project Developers
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// - Redistributions of source code must retain the above copyright
//   notice, this list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright
//   notice, this list of conditions and the following disclaimer in
//   the documentation and/or other materials provided with the
//   distribution.
//
// - Neither the name of "The Computer Language Benchmarks Game" nor
//   the name of "The Computer Language Shootout Benchmarks" nor the
//   names of its contributors may be used to endorse or promote
//   products derived from this software without specific prior
//   written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
// OF THE POSSIBILITY OF SUCH DAMAGE.

// ignore-android doesn't terminate?

#![feature(slicing_syntax, asm, if_let, tuple_indexing)]

extern crate libc;

use std::io::stdio::{stdin_raw, stdout_raw};
use std::sync::{Future};
use std::num::{div_rem};
use std::ptr::{copy_memory};
use std::io::{IoResult, EndOfFile};
use std::slice::raw::{mut_buf_as_slice};

use shared_memory::{SharedMemory};

mod tables {
    use std::sync::{Once, ONCE_INIT};

    /// Lookup tables.
    static mut CPL16: [u16, ..1 << 16] = [0, ..1 << 16];
    static mut CPL8:  [u8,  ..1 << 8]  = [0, ..1 << 8];

    /// Generates the tables.
    pub fn get() -> Tables {
        /// To make sure we initialize the tables only once.
        static INIT: Once = ONCE_INIT;
        INIT.doit(|| {
            unsafe {
                for i in range(0, 1 << 8) {
                    CPL8[i] = match i as u8 {
                        b'A' | b'a' => b'T',
                        b'C' | b'c' => b'G',
                        b'G' | b'g' => b'C',
                        b'T' | b't' => b'A',
                        b'U' | b'u' => b'A',
                        b'M' | b'm' => b'K',
                        b'R' | b'r' => b'Y',
                        b'W' | b'w' => b'W',
                        b'S' | b's' => b'S',
                        b'Y' | b'y' => b'R',
                        b'K' | b'k' => b'M',
                        b'V' | b'v' => b'B',
                        b'H' | b'h' => b'D',
                        b'D' | b'd' => b'H',
                        b'B' | b'b' => b'V',
                        b'N' | b'n' => b'N',
                        i => i,
                    };
                }

                for (i, v) in CPL16.iter_mut().enumerate() {
                    *v = *CPL8.unsafe_get(i & 255) as u16 << 8 |
                         *CPL8.unsafe_get(i >> 8)  as u16;
                }
            }
        });
        Tables { _dummy: () }
    }

    /// Accessor for the static arrays.
    ///
    /// To make sure that the tables can't be accessed without having been initialized.
    pub struct Tables {
        _dummy: ()
    }

    impl Tables {
        /// Retreives the complement for `i`.
        pub fn cpl8(self, i: u8) -> u8 {
            // Not really unsafe.
            unsafe { CPL8[i as uint] }
        }

        /// Retreives the complement for `i`.
        pub fn cpl16(self, i: u16) -> u16 {
            unsafe { CPL16[i as uint] }
        }
    }
}

mod shared_memory {
    use std::sync::{Arc};
    use std::mem::{transmute};
    use std::raw::{Slice};

    /// Structure for sharing disjoint parts of a vector mutably across tasks.
    pub struct SharedMemory {
        ptr: Arc<Vec<u8>>,
        start: uint,
        len: uint,
    }

    impl SharedMemory {
        pub fn new(ptr: Vec<u8>) -> SharedMemory {
            let len = ptr.len();
            SharedMemory {
                ptr: Arc::new(ptr),
                start: 0,
                len: len,
            }
        }

        pub fn as_mut_slice(&mut self) -> &mut [u8] {
            unsafe {
                transmute(Slice {
                    data: self.ptr.as_ptr().offset(self.start as int) as *const u8,
                    len: self.len,
                })
            }
        }

        pub fn len(&self) -> uint {
            self.len
        }

        pub fn split_at(self, mid: uint) -> (SharedMemory, SharedMemory) {
            assert!(mid <= self.len);
            let left = SharedMemory {
                ptr: self.ptr.clone(),
                start: self.start,
                len: mid,
            };
            let right = SharedMemory {
                ptr: self.ptr,
                start: self.start + mid,
                len: self.len - mid,
            };
            (left, right)
        }

        /// Resets the object so that it covers the whole range of the contained vector.
        ///
        /// You must not call this method if `self` is not the only reference to the
        /// shared memory.
        ///
        /// FIXME: If `Arc` had a method to check if the reference is unique, then we
        /// wouldn't need the `unsafe` here.
        ///
        /// FIXME: If `Arc` had a method to unwrap the contained value, then we could
        /// simply unwrap here.
        pub unsafe fn reset(self) -> SharedMemory {
            let len = self.ptr.len();
            SharedMemory {
                ptr: self.ptr,
                start: 0,
                len: len,
            }
        }
    }
}

/// Reads all remaining bytes from the stream.
fn read_to_end<R: Reader>(r: &mut R) -> IoResult<Vec<u8>> {
    const CHUNK: uint = 64 * 1024;

    let mut vec = Vec::with_capacity(1024 * 1024);
    loop {
        if vec.capacity() - vec.len() < CHUNK {
            let cap = vec.capacity();
            let mult = if cap < 256 * 1024 * 1024 {
                // FIXME (mahkoh): Temporary workaround for jemalloc on linux. Replace
                // this by 2x once the jemalloc preformance issue has been fixed.
                16
            } else {
                2
            };
            vec.reserve_exact(mult * cap);
        }
        unsafe {
            let ptr = vec.as_mut_ptr().offset(vec.len() as int);
            match mut_buf_as_slice(ptr, CHUNK, |s| r.read(s)) {
                Ok(n) => {
                    let len = vec.len();
                    vec.set_len(len + n);
                },
                Err(ref e) if e.kind == EndOfFile => break,
                Err(e) => return Err(e),
            }
        }
    }
    Ok(vec)
}

/// Finds the first position at which `b` occurs in `s`.
fn memchr(h: &[u8], n: u8) -> Option<uint> {
    use libc::{c_void, c_int, size_t};
    extern {
        fn memchr(h: *const c_void, n: c_int, s: size_t) -> *mut c_void;
    }
    let res = unsafe {
        memchr(h.as_ptr() as *const c_void, n as c_int, h.len() as size_t)
    };
    if res.is_null() {
        None
    } else {
        Some(res as uint - h.as_ptr() as uint)
    }
}

/// Length of a normal line without the terminating \n.
const LINE_LEN: uint = 60;

/// Compute the reverse complement.
fn reverse_complement(mut view: SharedMemory, tables: tables::Tables) {
    // Drop the last newline
    let seq = view.as_mut_slice().init_mut();
    let len = seq.len();
    let off = LINE_LEN - len % (LINE_LEN + 1);
    let mut i = LINE_LEN;
    while i < len {
        unsafe {
            copy_memory(seq.as_mut_ptr().offset((i - off + 1) as int),
                        seq.as_ptr().offset((i - off) as int), off);
            *seq.unsafe_mut(i - off) = b'\n';
        }
        i += LINE_LEN + 1;
    }

    let (div, rem) = div_rem(len, 4);
    unsafe {
        let mut left = seq.as_mut_ptr() as *mut u16;
        // This is slow if len % 2 != 0 but still faster than bytewise operations.
        let mut right = seq.as_mut_ptr().offset(len as int - 2) as *mut u16;
        let end = left.offset(div as int);
        while left != end {
            let tmp = tables.cpl16(*left);
            *left = tables.cpl16(*right);
            *right = tmp;
            left = left.offset(1);
            right = right.offset(-1);
        }

        let end = end as *mut u8;
        match rem {
            1 => *end = tables.cpl8(*end),
            2 => {
                let tmp = tables.cpl8(*end);
                *end = tables.cpl8(*end.offset(1));
                *end.offset(1) = tmp;
            },
            3 => {
                *end.offset(1) = tables.cpl8(*end.offset(1));
                let tmp = tables.cpl8(*end);
                *end = tables.cpl8(*end.offset(2));
                *end.offset(2) = tmp;
            },
            _ => { },
        }
    }
}

fn main() {
    let mut data = SharedMemory::new(read_to_end(&mut stdin_raw()).unwrap());
    let tables = tables::get();

    let mut futures = vec!();
    loop {
        let (_, mut tmp_data) = match memchr(data.as_mut_slice(), b'\n') {
            Some(i) => data.split_at(i + 1),
            _ => break,
        };
        let (view, tmp_data) = match memchr(tmp_data.as_mut_slice(), b'>') {
            Some(i) => tmp_data.split_at(i),
            None => {
                let len = tmp_data.len();
                tmp_data.split_at(len)
            },
        };
        futures.push(Future::spawn(proc() reverse_complement(view, tables)));
        data = tmp_data;
    }

    for f in futures.iter_mut() {
        f.get();
    }

    // Not actually unsafe. If Arc had a way to check uniqueness then we could do that in
    // `reset` and it would tell us that, yes, it is unique at this point.
    data = unsafe { data.reset() };

    stdout_raw().write(data.as_mut_slice()).unwrap();
}
<|endoftext|>


<commit_before><commit_msg>parser: make the parser aware of lists<commit_after><|endoftext|>


<commit_before><commit_msg>clear fix<commit_after><|endoftext|>


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

/** Task-local reference counted boxes

The `Rc` type provides shared ownership of an immutable value. Destruction is deterministic, and
will occur as soon as the last owner is gone. It is marked as non-sendable because it avoids the
overhead of atomic reference counting.

The `RcMut` type provides shared ownership of a mutable value. Since multiple owners prevent
inherited mutability, a dynamic freezing check is used to maintain the invariant that an `&mut`
reference is a unique handle and the type is marked as non-`Freeze`.

*/

use ptr::RawPtr;
use unstable::intrinsics::transmute;
use ops::Drop;
use kinds::{Freeze, Send};
use clone::{Clone, DeepClone};

struct RcBox<T> {
    value: T,
    count: uint
}

/// Immutable reference counted pointer type
#[unsafe_no_drop_flag]
#[no_send]
pub struct Rc<T> {
    priv ptr: *mut RcBox<T>
}

impl<T: Freeze> Rc<T> {
    /// Construct a new reference-counted box from a `Freeze` value
    #[inline]
    pub fn new(value: T) -> Rc<T> {
        unsafe {
            Rc::new_unchecked(value)
        }
    }
}

impl<T> Rc<T> {
    /// Unsafety construct a new reference-counted box from any value.
    ///
    /// If the type is not `Freeze`, the `Rc` box will incorrectly still be considered as a `Freeze`
    /// type. It is also possible to create cycles, which will leak, and may interact poorly with
    /// managed pointers.
    #[inline]
    pub unsafe fn new_unchecked(value: T) -> Rc<T> {
        Rc{ptr: transmute(~RcBox{value: value, count: 1})}
    }

    /// Borrow the value contained in the reference-counted box
    #[inline]
    pub fn borrow<'r>(&'r self) -> &'r T {
        unsafe { &(*self.ptr).value }
    }
}

impl<T> Clone for Rc<T> {
    #[inline]
    fn clone(&self) -> Rc<T> {
        unsafe {
            (*self.ptr).count += 1;
            Rc{ptr: self.ptr}
        }
    }
}

impl<T: DeepClone> DeepClone for Rc<T> {
    #[inline]
    fn deep_clone(&self) -> Rc<T> {
        unsafe { Rc::new_unchecked(self.borrow().deep_clone()) }
    }
}

#[unsafe_destructor]
impl<T> Drop for Rc<T> {
    fn drop(&mut self) {
        unsafe {
            if self.ptr.is_not_null() {
                (*self.ptr).count -= 1;
                if (*self.ptr).count == 0 {
                    let _: ~RcBox<T> = transmute(self.ptr);
                }
            }
        }
    }
}

#[cfg(test)]
mod test_rc {
    use super::*;
    use cell::Cell;

    #[test]
    fn test_clone() {
        unsafe {
            let x = Rc::new_unchecked(Cell::new(5));
            let y = x.clone();
            do x.borrow().with_mut_ref |inner| {
                *inner = 20;
            }
            assert_eq!(y.borrow().take(), 20);
        }
    }

    #[test]
    fn test_deep_clone() {
        unsafe {
            let x = Rc::new_unchecked(Cell::new(5));
            let y = x.deep_clone();
            do x.borrow().with_mut_ref |inner| {
                *inner = 20;
            }
            assert_eq!(y.borrow().take(), 5);
        }
    }

    #[test]
    fn test_simple() {
        let x = Rc::new(5);
        assert_eq!(*x.borrow(), 5);
    }

    #[test]
    fn test_simple_clone() {
        let x = Rc::new(5);
        let y = x.clone();
        assert_eq!(*x.borrow(), 5);
        assert_eq!(*y.borrow(), 5);
    }

    #[test]
    fn test_destructor() {
        unsafe {
            let x = Rc::new_unchecked(~5);
            assert_eq!(**x.borrow(), 5);
        }
    }
}

#[deriving(Eq)]
enum Borrow {
    Mutable,
    Immutable,
    Nothing
}

struct RcMutBox<T> {
    value: T,
    count: uint,
    borrow: Borrow
}

/// Mutable reference counted pointer type
#[no_send]
#[no_freeze]
#[unsafe_no_drop_flag]
pub struct RcMut<T> {
    priv ptr: *mut RcMutBox<T>,
}

impl<T: Freeze> RcMut<T> {
    /// Construct a new mutable reference-counted box from a `Freeze` value
    #[inline]
    pub fn new(value: T) -> RcMut<T> {
        unsafe { RcMut::new_unchecked(value) }
    }
}

impl<T: Send> RcMut<T> {
    /// Construct a new mutable reference-counted box from a `Send` value
    #[inline]
    pub fn from_send(value: T) -> RcMut<T> {
        unsafe { RcMut::new_unchecked(value) }
    }
}

impl<T> RcMut<T> {
    /// Unsafety construct a new mutable reference-counted box from any value.
    ///
    /// It is possible to create cycles, which will leak, and may interact
    /// poorly with managed pointers.
    #[inline]
    pub unsafe fn new_unchecked(value: T) -> RcMut<T> {
        RcMut{ptr: transmute(~RcMutBox{value: value, count: 1, borrow: Nothing})}
    }
}

impl<T> RcMut<T> {
    /// Fails if there is already a mutable borrow of the box
    #[inline]
    pub fn with_borrow<U>(&self, f: &fn(&T) -> U) -> U {
        unsafe {
            assert!((*self.ptr).borrow != Mutable);
            let previous = (*self.ptr).borrow;
            (*self.ptr).borrow = Immutable;
            let res = f(&(*self.ptr).value);
            (*self.ptr).borrow = previous;
            res
        }
    }

    /// Fails if there is already a mutable or immutable borrow of the box
    #[inline]
    pub fn with_mut_borrow<U>(&self, f: &fn(&mut T) -> U) -> U {
        unsafe {
            assert_eq!((*self.ptr).borrow, Nothing);
            (*self.ptr).borrow = Mutable;
            let res = f(&mut (*self.ptr).value);
            (*self.ptr).borrow = Nothing;
            res
        }
    }
}

#[unsafe_destructor]
impl<T> Drop for RcMut<T> {
    fn drop(&mut self) {
        unsafe {
            if self.ptr.is_not_null() {
                (*self.ptr).count -= 1;
                if (*self.ptr).count == 0 {
                    let _: ~RcMutBox<T> = transmute(self.ptr);
                }
            }
        }
    }
}

impl<T> Clone for RcMut<T> {
    /// Return a shallow copy of the reference counted pointer.
    #[inline]
    fn clone(&self) -> RcMut<T> {
        unsafe {
            (*self.ptr).count += 1;
            RcMut{ptr: self.ptr}
        }
    }
}

impl<T: DeepClone> DeepClone for RcMut<T> {
    /// Return a deep copy of the reference counted pointer.
    #[inline]
    fn deep_clone(&self) -> RcMut<T> {
        do self.with_borrow |x| {
            // FIXME: #6497: should avoid freeze (slow)
            unsafe { RcMut::new_unchecked(x.deep_clone()) }
        }
    }
}

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

    #[test]
    fn test_clone() {
        let x = RcMut::from_send(5);
        let y = x.clone();
        do x.with_mut_borrow |value| {
            *value = 20;
        }
        do y.with_borrow |value| {
            assert_eq!(*value, 20);
        }
    }

    #[test]
    fn test_deep_clone() {
        let x = RcMut::new(5);
        let y = x.deep_clone();
        do x.with_mut_borrow |value| {
            *value = 20;
        }
        do y.with_borrow |value| {
            assert_eq!(*value, 5);
        }
    }

    #[test]
    fn borrow_many() {
        let x = RcMut::from_send(5);
        let y = x.clone();

        do x.with_borrow |a| {
            assert_eq!(*a, 5);
            do y.with_borrow |b| {
                assert_eq!(*b, 5);
                do x.with_borrow |c| {
                    assert_eq!(*c, 5);
                }
            }
        }
    }

    #[test]
    fn modify() {
        let x = RcMut::new(5);
        let y = x.clone();

        do y.with_mut_borrow |a| {
            assert_eq!(*a, 5);
            *a = 6;
        }

        do x.with_borrow |a| {
            assert_eq!(*a, 6);
        }
    }

    #[test]
    fn release_immutable() {
        let x = RcMut::from_send(5);
        do x.with_borrow |_| {}
        do x.with_mut_borrow |_| {}
    }

    #[test]
    fn release_mutable() {
        let x = RcMut::new(5);
        do x.with_mut_borrow |_| {}
        do x.with_borrow |_| {}
    }

    #[test]
    #[should_fail]
    fn frozen() {
        let x = RcMut::from_send(5);
        let y = x.clone();

        do x.with_borrow |_| {
            do y.with_mut_borrow |_| {
            }
        }
    }

    #[test]
    #[should_fail]
    fn mutable_dupe() {
        let x = RcMut::new(5);
        let y = x.clone();

        do x.with_mut_borrow |_| {
            do y.with_mut_borrow |_| {
            }
        }
    }

    #[test]
    #[should_fail]
    fn mutable_freeze() {
        let x = RcMut::from_send(5);
        let y = x.clone();

        do x.with_mut_borrow |_| {
            do y.with_borrow |_| {
            }
        }
    }

    #[test]
    #[should_fail]
    fn restore_freeze() {
        let x = RcMut::new(5);
        let y = x.clone();

        do x.with_borrow |_| {
            do x.with_borrow |_| {}
            do y.with_mut_borrow |_| {}
        }
    }
}
<commit_msg>rc: fix docstring<commit_after>// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

/*! Task-local reference counted boxes

The `Rc` type provides shared ownership of an immutable value. Destruction is deterministic, and
will occur as soon as the last owner is gone. It is marked as non-sendable because it avoids the
overhead of atomic reference counting.

The `RcMut` type provides shared ownership of a mutable value. Since multiple owners prevent
inherited mutability, a dynamic freezing check is used to maintain the invariant that an `&mut`
reference is a unique handle and the type is marked as non-`Freeze`.

*/

use ptr::RawPtr;
use unstable::intrinsics::transmute;
use ops::Drop;
use kinds::{Freeze, Send};
use clone::{Clone, DeepClone};

struct RcBox<T> {
    value: T,
    count: uint
}

/// Immutable reference counted pointer type
#[unsafe_no_drop_flag]
#[no_send]
pub struct Rc<T> {
    priv ptr: *mut RcBox<T>
}

impl<T: Freeze> Rc<T> {
    /// Construct a new reference-counted box from a `Freeze` value
    #[inline]
    pub fn new(value: T) -> Rc<T> {
        unsafe {
            Rc::new_unchecked(value)
        }
    }
}

impl<T> Rc<T> {
    /// Unsafety construct a new reference-counted box from any value.
    ///
    /// If the type is not `Freeze`, the `Rc` box will incorrectly still be considered as a `Freeze`
    /// type. It is also possible to create cycles, which will leak, and may interact poorly with
    /// managed pointers.
    #[inline]
    pub unsafe fn new_unchecked(value: T) -> Rc<T> {
        Rc{ptr: transmute(~RcBox{value: value, count: 1})}
    }

    /// Borrow the value contained in the reference-counted box
    #[inline]
    pub fn borrow<'r>(&'r self) -> &'r T {
        unsafe { &(*self.ptr).value }
    }
}

impl<T> Clone for Rc<T> {
    #[inline]
    fn clone(&self) -> Rc<T> {
        unsafe {
            (*self.ptr).count += 1;
            Rc{ptr: self.ptr}
        }
    }
}

impl<T: DeepClone> DeepClone for Rc<T> {
    #[inline]
    fn deep_clone(&self) -> Rc<T> {
        unsafe { Rc::new_unchecked(self.borrow().deep_clone()) }
    }
}

#[unsafe_destructor]
impl<T> Drop for Rc<T> {
    fn drop(&mut self) {
        unsafe {
            if self.ptr.is_not_null() {
                (*self.ptr).count -= 1;
                if (*self.ptr).count == 0 {
                    let _: ~RcBox<T> = transmute(self.ptr);
                }
            }
        }
    }
}

#[cfg(test)]
mod test_rc {
    use super::*;
    use cell::Cell;

    #[test]
    fn test_clone() {
        unsafe {
            let x = Rc::new_unchecked(Cell::new(5));
            let y = x.clone();
            do x.borrow().with_mut_ref |inner| {
                *inner = 20;
            }
            assert_eq!(y.borrow().take(), 20);
        }
    }

    #[test]
    fn test_deep_clone() {
        unsafe {
            let x = Rc::new_unchecked(Cell::new(5));
            let y = x.deep_clone();
            do x.borrow().with_mut_ref |inner| {
                *inner = 20;
            }
            assert_eq!(y.borrow().take(), 5);
        }
    }

    #[test]
    fn test_simple() {
        let x = Rc::new(5);
        assert_eq!(*x.borrow(), 5);
    }

    #[test]
    fn test_simple_clone() {
        let x = Rc::new(5);
        let y = x.clone();
        assert_eq!(*x.borrow(), 5);
        assert_eq!(*y.borrow(), 5);
    }

    #[test]
    fn test_destructor() {
        unsafe {
            let x = Rc::new_unchecked(~5);
            assert_eq!(**x.borrow(), 5);
        }
    }
}

#[deriving(Eq)]
enum Borrow {
    Mutable,
    Immutable,
    Nothing
}

struct RcMutBox<T> {
    value: T,
    count: uint,
    borrow: Borrow
}

/// Mutable reference counted pointer type
#[no_send]
#[no_freeze]
#[unsafe_no_drop_flag]
pub struct RcMut<T> {
    priv ptr: *mut RcMutBox<T>,
}

impl<T: Freeze> RcMut<T> {
    /// Construct a new mutable reference-counted box from a `Freeze` value
    #[inline]
    pub fn new(value: T) -> RcMut<T> {
        unsafe { RcMut::new_unchecked(value) }
    }
}

impl<T: Send> RcMut<T> {
    /// Construct a new mutable reference-counted box from a `Send` value
    #[inline]
    pub fn from_send(value: T) -> RcMut<T> {
        unsafe { RcMut::new_unchecked(value) }
    }
}

impl<T> RcMut<T> {
    /// Unsafety construct a new mutable reference-counted box from any value.
    ///
    /// It is possible to create cycles, which will leak, and may interact
    /// poorly with managed pointers.
    #[inline]
    pub unsafe fn new_unchecked(value: T) -> RcMut<T> {
        RcMut{ptr: transmute(~RcMutBox{value: value, count: 1, borrow: Nothing})}
    }
}

impl<T> RcMut<T> {
    /// Fails if there is already a mutable borrow of the box
    #[inline]
    pub fn with_borrow<U>(&self, f: &fn(&T) -> U) -> U {
        unsafe {
            assert!((*self.ptr).borrow != Mutable);
            let previous = (*self.ptr).borrow;
            (*self.ptr).borrow = Immutable;
            let res = f(&(*self.ptr).value);
            (*self.ptr).borrow = previous;
            res
        }
    }

    /// Fails if there is already a mutable or immutable borrow of the box
    #[inline]
    pub fn with_mut_borrow<U>(&self, f: &fn(&mut T) -> U) -> U {
        unsafe {
            assert_eq!((*self.ptr).borrow, Nothing);
            (*self.ptr).borrow = Mutable;
            let res = f(&mut (*self.ptr).value);
            (*self.ptr).borrow = Nothing;
            res
        }
    }
}

#[unsafe_destructor]
impl<T> Drop for RcMut<T> {
    fn drop(&mut self) {
        unsafe {
            if self.ptr.is_not_null() {
                (*self.ptr).count -= 1;
                if (*self.ptr).count == 0 {
                    let _: ~RcMutBox<T> = transmute(self.ptr);
                }
            }
        }
    }
}

impl<T> Clone for RcMut<T> {
    /// Return a shallow copy of the reference counted pointer.
    #[inline]
    fn clone(&self) -> RcMut<T> {
        unsafe {
            (*self.ptr).count += 1;
            RcMut{ptr: self.ptr}
        }
    }
}

impl<T: DeepClone> DeepClone for RcMut<T> {
    /// Return a deep copy of the reference counted pointer.
    #[inline]
    fn deep_clone(&self) -> RcMut<T> {
        do self.with_borrow |x| {
            // FIXME: #6497: should avoid freeze (slow)
            unsafe { RcMut::new_unchecked(x.deep_clone()) }
        }
    }
}

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

    #[test]
    fn test_clone() {
        let x = RcMut::from_send(5);
        let y = x.clone();
        do x.with_mut_borrow |value| {
            *value = 20;
        }
        do y.with_borrow |value| {
            assert_eq!(*value, 20);
        }
    }

    #[test]
    fn test_deep_clone() {
        let x = RcMut::new(5);
        let y = x.deep_clone();
        do x.with_mut_borrow |value| {
            *value = 20;
        }
        do y.with_borrow |value| {
            assert_eq!(*value, 5);
        }
    }

    #[test]
    fn borrow_many() {
        let x = RcMut::from_send(5);
        let y = x.clone();

        do x.with_borrow |a| {
            assert_eq!(*a, 5);
            do y.with_borrow |b| {
                assert_eq!(*b, 5);
                do x.with_borrow |c| {
                    assert_eq!(*c, 5);
                }
            }
        }
    }

    #[test]
    fn modify() {
        let x = RcMut::new(5);
        let y = x.clone();

        do y.with_mut_borrow |a| {
            assert_eq!(*a, 5);
            *a = 6;
        }

        do x.with_borrow |a| {
            assert_eq!(*a, 6);
        }
    }

    #[test]
    fn release_immutable() {
        let x = RcMut::from_send(5);
        do x.with_borrow |_| {}
        do x.with_mut_borrow |_| {}
    }

    #[test]
    fn release_mutable() {
        let x = RcMut::new(5);
        do x.with_mut_borrow |_| {}
        do x.with_borrow |_| {}
    }

    #[test]
    #[should_fail]
    fn frozen() {
        let x = RcMut::from_send(5);
        let y = x.clone();

        do x.with_borrow |_| {
            do y.with_mut_borrow |_| {
            }
        }
    }

    #[test]
    #[should_fail]
    fn mutable_dupe() {
        let x = RcMut::new(5);
        let y = x.clone();

        do x.with_mut_borrow |_| {
            do y.with_mut_borrow |_| {
            }
        }
    }

    #[test]
    #[should_fail]
    fn mutable_freeze() {
        let x = RcMut::from_send(5);
        let y = x.clone();

        do x.with_mut_borrow |_| {
            do y.with_borrow |_| {
            }
        }
    }

    #[test]
    #[should_fail]
    fn restore_freeze() {
        let x = RcMut::new(5);
        let y = x.clone();

        do x.with_borrow |_| {
            do x.with_borrow |_| {}
            do y.with_mut_borrow |_| {}
        }
    }
}
<|endoftext|>