<commit_before>extern mod portaudio;

use std::io;

use portaudio::*;

fn main() -> () {
    io::println(fmt!("Portaudio version : %d", pa::get_version() as int));
    io::println(fmt!("Portaudio version text : %s", pa::get_version_text()));
    io::println(fmt!("Portaudio error text : %s", pa::get_error_text(types::PaNotInitialized)));

    io::println(fmt!("Portaudio init error : %s", pa::get_error_text(pa::initialize())));

    let host_count = pa::get_host_api_count();
    io::println(fmt!("Portaudio host count : %d", host_count as int));

    let default_host = pa::get_default_host_api();
    io::println(fmt!("Portaudio default host : %d", default_host as int));

    let host_info = pa::get_host_api_info(default_host);
    io::println(fmt!("Portaudio host name : %s", host_info.unwrap().name));

    io::println(fmt!("Portaudio type id : %d",
                    pa::host_api_type_id_to_host_api_index(types::PaCoreAudio) as int));

    let def_input = pa::get_default_input_device();
    let info_input = pa::get_device_info(def_input).unwrap();
    io::println("Default input device info :");
    io::println(fmt!("version : %d", info_input.struct_version));
    io::println(fmt!("name : %s", info_input.name));
    io::println(fmt!("max input channels : %d", info_input.max_input_channels));
    io::println(fmt!("max output channels : %d", info_input.max_output_channels));
    io::println(fmt!("default sample rate : %f", info_input.default_sample_rate as float));

    if pa::get_device_info(def_input).is_none() {
        io::println("BOULET");
    }
    // PaStream test :
    let stream_params  = types::PaStreamParameters {
        device : def_input,
        channel_count : 2,
        sample_format : types::PaFloat32,
        suggested_latency : pa::get_device_info(def_input).unwrap().default_low_input_latency
    };

    let def_output = pa::get_default_output_device();
    io::println(fmt!("name : %s", pa::get_device_info(def_output).unwrap().name));

    let stream_params_out = types::PaStreamParameters {
        device : def_output,
        channel_count : 2,
        sample_format : types::PaFloat32,
        suggested_latency : pa::get_device_info(def_output).unwrap().default_low_output_latency
    };

    let mut stream : pa::PaStream<f32, f32> = pa::PaStream::new(types::PaFloat32);

    let mut err= stream.open(Some(&stream_params), Some(&stream_params_out), 44100., 1024, types::PaClipOff);

    io::println(fmt!("Portaudio Open error : %s", pa::get_error_text(err)));

    io::println(fmt!("Stream is active : %s", pa::get_error_text(stream.is_active())));

    err = stream.start();
    io::println(fmt!("Portaudio Start error : %s", pa::get_error_text(err)));

    let mut test;
    loop {
        test = stream.get_stream_write_available();
        while test == 0 {
            test = stream.get_stream_write_available();
        }
            io::println(fmt!("Stream Write available : %d", test as int));

        match stream.read(1024) {
            Ok(res)     => {
                // for i in res.iter() {
                //     io::println(fmt!("%f", *i as float));
                // }
                stream.write(res, 1024)
            },
            Err(err)    => fail!(fmt!("Portaudio error read : %s", pa::get_error_text(err)))
        };
    }

    err = types::PaNotInitialized;

    err = stream.close();
    io::println(fmt!("Portaudio Close stream error : %s", pa::get_error_text(err)));

    io::println("");

    io::println(fmt!("Portaudio terminate error : %s", pa::get_error_text(pa::terminate())));
}
<commit_msg>make test main compile on current rust master<commit_after>#[feature(globs)];

extern mod portaudio;

use portaudio::*;

fn main() -> () {
    println!("Portaudio version : {}", pa::get_version());
    println!("Portaudio version text : {}", pa::get_version_text());
    println!("Portaudio error text : {}", pa::get_error_text(types::PaNotInitialized));

    println!("Portaudio init error : {}", pa::get_error_text(pa::initialize()));

    let host_count = pa::get_host_api_count();
    println!("Portaudio host count : {}", host_count as int);

    let default_host = pa::get_default_host_api();
    println!("Portaudio default host : {}", default_host as int);

    let host_info = pa::get_host_api_info(default_host);
    println!("Portaudio host name : {}", host_info.unwrap().name);

    println!("Portaudio type id : {}",
             pa::host_api_type_id_to_host_api_index(types::PaCoreAudio) as int);

    let def_input = pa::get_default_input_device();
    let info_input = pa::get_device_info(def_input).unwrap();
    println!("Default input device info :");
    println!("version : {}", info_input.struct_version);
    println!("name : {}", info_input.name);
    println!("max input channels : {}", info_input.max_input_channels);
    println!("max output channels : {}", info_input.max_output_channels);
    println!("default sample rate : {}", info_input.default_sample_rate);

    if pa::get_device_info(def_input).is_none() {
       println!("error");
    }
    // PaStream test :
    let stream_params  = types::PaStreamParameters {
        device : def_input,
        channel_count : 2,
        sample_format : types::PaFloat32,
        suggested_latency : pa::get_device_info(def_input).unwrap().default_low_input_latency
    };

    let def_output = pa::get_default_output_device();
    println!("name : {}", pa::get_device_info(def_output).unwrap().name);

    let stream_params_out = types::PaStreamParameters {
        device : def_output,
        channel_count : 2,
        sample_format : types::PaFloat32,
        suggested_latency : pa::get_device_info(def_output).unwrap().default_low_output_latency
    };

    let mut stream : pa::PaStream<f32> = pa::PaStream::new(types::PaFloat32);

    let mut err= stream.open(Some(&stream_params), Some(&stream_params_out), 44100., 1024, types::PaClipOff);

    println!("Portaudio Open error : {}", pa::get_error_text(err));

    //println!("Stream is active : {}", pa::get_error_text(stream.is_active().unwrap()));

    err = stream.start();
    println!("Portaudio Start error : {}", pa::get_error_text(err));

    let mut test;
    loop {
        test = stream.get_stream_write_available();
        while test == 0 {
            test = stream.get_stream_write_available();
        }
            println!("Stream Write available : {}", test as int);

        match stream.read(1024) {
            Ok(res)     => {
                // for i in res.iter() {
                //     io::println(fmt!("%f", *i as float));
                // }
                stream.write(res, 1024)
            },
            Err(err)    => fail!(format!("Portaudio error read : {}", pa::get_error_text(err)))
        };
    }

    err = types::PaNotInitialized;

    err = stream.close();
    println!("Portaudio Close stream error : {}", pa::get_error_text(err));

    println!("");

    println!("Portaudio terminate error : {}", pa::get_error_text(pa::terminate()));
}
<|endoftext|>


<commit_before>extern crate test;

use std::mem::size_of;
use std::old_io::{File, SeekSet};
use std::path;
use std::fs::PathExt;

use {open, B, M, BmpError, BmpErrorKind, BmpId, BmpHeader, BmpDibHeader, Image, Pixel};
use consts;

#[test]
fn size_of_bmp_header_is_54_bytes() {
    let bmp_magic_size = size_of::<BmpId>();
    let bmp_header_size = size_of::<BmpHeader>();
    let bmp_bip_header_size = size_of::<BmpDibHeader>();

    assert_eq!(2,  bmp_magic_size);
    assert_eq!(12, bmp_header_size);
    assert_eq!(40, bmp_bip_header_size);
}

#[test]
fn size_of_4pixel_bmp_image_is_70_bytes() {
    let path_wd = path::Path::new("test/rgbw.bmp");
    match path_wd.metadata() {
        Ok(stat) => assert_eq!(70, stat.len() as i32),
        Err(_) => (/* Ignore IoError for now */)
    }
}

fn verify_test_bmp_image(img: Image) {
    let header = img.header;
    assert_eq!(70, header.file_size);
    assert_eq!(0,  header.creator1);
    assert_eq!(0,  header.creator2);

    let dib_header = img.dib_header;
    assert_eq!(54, header.pixel_offset);
    assert_eq!(40,    dib_header.header_size);
    assert_eq!(2,     dib_header.width);
    assert_eq!(2,     dib_header.height);
    assert_eq!(1,     dib_header.num_planes);
    assert_eq!(24,    dib_header.bits_per_pixel);
    assert_eq!(0,     dib_header.compress_type);
    assert_eq!(16,    dib_header.data_size);
    assert_eq!(1000, dib_header.hres);
    assert_eq!(1000, dib_header.vres);
    assert_eq!(0,     dib_header.num_colors);
    assert_eq!(0,     dib_header.num_imp_colors);

    assert_eq!(2, img.padding);
}

#[test]
fn can_read_bmp_image() {
    let bmp_img = open("test/rgbw.bmp").unwrap();
    verify_test_bmp_image(bmp_img);
}

#[test]
fn can_read_image_data() {
    let mut f = match File::open(&Path::new("test/rgbw.bmp")) {
        Ok(file) => file,
        Err(e) => panic!("File error: {}", e)
    };
    assert_eq!(B, f.read_byte().unwrap());
    assert_eq!(M, f.read_byte().unwrap());

    match f.seek(54, SeekSet) {
        Ok(_) => (),
        Err(e) => panic!("Seek error: {}", e)
    }

    let pixel = Pixel {
        r: f.read_byte().unwrap(),
        g: f.read_byte().unwrap(),
        b: f.read_byte().unwrap()
    };

    assert_eq!(pixel, consts::RED);
}

#[test]
fn can_read_entire_bmp_image() {
    let bmp_img = open("test/rgbw.bmp").unwrap();
    assert_eq!(bmp_img.data.len(), 4);

    assert_eq!(bmp_img.get_pixel(0, 0), consts::RED);
    assert_eq!(bmp_img.get_pixel(1, 0), consts::LIME);
    assert_eq!(bmp_img.get_pixel(0, 1), consts::BLUE);
    assert_eq!(bmp_img.get_pixel(1, 1), consts::WHITE);
}

#[test]
fn read_write_1pbb_bmp_image() {
    let img = open("test/bmptestsuite-0.9/valid/1bpp-1x1.bmp").unwrap();
    assert_eq!(img.data.len(), 1);
    assert_eq!(img.get_pixel(0, 0), consts::BLACK);

    let _ = img.save("test/1bb-1x1.bmp");
    let img = open("test/1bb-1x1.bmp").unwrap();
    assert_eq!(img.data.len(), 1);
    assert_eq!(img.get_pixel(0, 0), consts::BLACK);
}

#[test]
fn read_write_4pbb_bmp_image() {
    let img = open("test/bmptestsuite-0.9/valid/4bpp-1x1.bmp").unwrap_or_else(|e| {
        panic!("{}", e);
    });
    assert_eq!(img.data.len(), 1);
    assert_eq!(img.get_pixel(0, 0), consts::BLUE);

    let _ = img.save("test/4bb-1x1.bmp");
    let img = open("test/4bb-1x1.bmp").unwrap_or_else(|e| {
        panic!("{}", e);
    });
    assert_eq!(img.data.len(), 1);
    assert_eq!(img.get_pixel(0, 0), consts::BLUE);
}

#[test]
fn read_write_8pbb_bmp_image() {
    let img = open("test/bmptestsuite-0.9/valid/8bpp-1x1.bmp").unwrap_or_else(|e| {
        panic!("{}", e);
    });
    assert_eq!(img.data.len(), 1);
    assert_eq!(img.get_pixel(0, 0), consts::BLUE);

    let _ = img.save("test/8bb-1x1.bmp");
    let img = open("test/8bb-1x1.bmp").unwrap_or_else(|e| {
        panic!("{}", e);
    });
    assert_eq!(img.data.len(), 1);
    assert_eq!(img.get_pixel(0, 0), consts::BLUE);
}

#[test]
fn error_when_opening_unexisting_image() {
    let result = open("test/no_img.bmp");
    match result {
        Err(BmpError{ kind: BmpErrorKind::BmpIoError(_), .. }) => (/* Expected */),
        _ => panic!("Ghost image!?")
    }
}

#[test]
fn error_when_opening_image_with_wrong_bits_per_pixel() {
    let result = open("test/bmptestsuite-0.9/valid/32bpp-1x1.bmp");
    match result {
        Err(BmpError { kind: BmpErrorKind::UnsupportedBitsPerPixel, .. }) => (/* Expected */),
        _ => panic!("32bpp should not be supported")
    }
}

#[test]
fn error_when_opening_image_with_wrong_magic_numbers() {
    let result = open("test/bmptestsuite-0.9/corrupt/magicnumber-bad.bmp");
    match result {
        Err(BmpError { kind: BmpErrorKind::WrongMagicNumbers, .. }) => (/* Expected */),
        _ => panic!("Wrong magic numbers should not be supported")
    }
}

#[test]
fn can_create_bmp_file() {
    let mut bmp = Image::new(2, 2);
    bmp.set_pixel(0, 0, consts::RED);
    bmp.set_pixel(1, 0, consts::LIME);
    bmp.set_pixel(0, 1, consts::BLUE);
    bmp.set_pixel(1, 1, consts::WHITE);
    let _ = bmp.save("test/rgbw_test.bmp");

    let bmp_img = open("test/rgbw_test.bmp").unwrap();
    assert_eq!(bmp_img.get_pixel(0, 0), consts::RED);
    assert_eq!(bmp_img.get_pixel(1, 0), consts::LIME);
    assert_eq!(bmp_img.get_pixel(0, 1), consts::BLUE);
    assert_eq!(bmp_img.get_pixel(1, 1), consts::WHITE);

    verify_test_bmp_image(bmp_img);
}

#[test]
fn changing_pixels_does_not_push_image_data() {
    let mut img = Image::new(2, 1);
    img.set_pixel(1, 0, consts::WHITE);
    img.set_pixel(0, 0, consts::WHITE);

    assert_eq!(img.get_pixel(0, 0), consts::WHITE);
    assert_eq!(img.get_pixel(1, 0), consts::WHITE);
}

#[test]
fn coordinates_iterator_gives_x_and_y_in_row_major_order() {
    let img = Image::new(2, 3);
    let mut coords = img.coordinates();
    assert_eq!(coords.next(), Some((0, 0)));
    assert_eq!(coords.next(), Some((1, 0)));
    assert_eq!(coords.next(), Some((0, 1)));
    assert_eq!(coords.next(), Some((1, 1)));
    assert_eq!(coords.next(), Some((0, 2)));
    assert_eq!(coords.next(), Some((1, 2)));
}

#[bench]
fn write_bmp(b: &mut test::Bencher) {
    let img = Image::new(320, 240);
    b.iter(|| img.save("test/bench_test.bmp"));
}

#[bench]
fn open_bmp(b: &mut test::Bencher) {
    b.iter(|| open("test/bmptestsuite-0.9/valid/24bpp-320x240.bmp"));
}
<commit_msg>Use new io in tests<commit_after>extern crate test;

use std::fs;
use std::fs::PathExt;
use std::io::{Read, Seek, SeekFrom};
use std::mem::size_of;
use std::path;

use {open, BmpError, BmpErrorKind, BmpId, BmpHeader, BmpDibHeader, Image, Pixel};
use consts;

#[test]
fn size_of_bmp_header_is_54_bytes() {
    let bmp_magic_size = size_of::<BmpId>();
    let bmp_header_size = size_of::<BmpHeader>();
    let bmp_bip_header_size = size_of::<BmpDibHeader>();

    assert_eq!(2,  bmp_magic_size);
    assert_eq!(12, bmp_header_size);
    assert_eq!(40, bmp_bip_header_size);
}

#[test]
fn size_of_4pixel_bmp_image_is_70_bytes() {
    let path_wd = path::Path::new("test/rgbw.bmp");
    match path_wd.metadata() {
        Ok(stat) => assert_eq!(70, stat.len() as i32),
        Err(_) => (/* Ignore IoError for now */)
    }
}

fn verify_test_bmp_image(img: Image) {
    let header = img.header;
    assert_eq!(70, header.file_size);
    assert_eq!(0,  header.creator1);
    assert_eq!(0,  header.creator2);

    let dib_header = img.dib_header;
    assert_eq!(54, header.pixel_offset);
    assert_eq!(40,    dib_header.header_size);
    assert_eq!(2,     dib_header.width);
    assert_eq!(2,     dib_header.height);
    assert_eq!(1,     dib_header.num_planes);
    assert_eq!(24,    dib_header.bits_per_pixel);
    assert_eq!(0,     dib_header.compress_type);
    assert_eq!(16,    dib_header.data_size);
    assert_eq!(1000, dib_header.hres);
    assert_eq!(1000, dib_header.vres);
    assert_eq!(0,     dib_header.num_colors);
    assert_eq!(0,     dib_header.num_imp_colors);

    assert_eq!(2, img.padding);
}

#[test]
fn can_read_bmp_image() {
    let bmp_img = open("test/rgbw.bmp").unwrap();
    verify_test_bmp_image(bmp_img);
}

#[test]
fn can_read_image_data() {
    let mut f = fs::File::open("test/rgbw.bmp").unwrap();
    f.seek(SeekFrom::Start(54)).unwrap();

    let mut px = [0; 3];
    f.read(&mut px).unwrap();

    assert_eq!(Pixel {r: px[2], g: px[1], b: px[0] }, consts::BLUE);
}

#[test]
fn can_read_entire_bmp_image() {
    let bmp_img = open("test/rgbw.bmp").unwrap();
    assert_eq!(bmp_img.data.len(), 4);

    assert_eq!(bmp_img.get_pixel(0, 0), consts::RED);
    assert_eq!(bmp_img.get_pixel(1, 0), consts::LIME);
    assert_eq!(bmp_img.get_pixel(0, 1), consts::BLUE);
    assert_eq!(bmp_img.get_pixel(1, 1), consts::WHITE);
}

#[test]
fn read_write_1pbb_bmp_image() {
    let img = open("test/bmptestsuite-0.9/valid/1bpp-1x1.bmp").unwrap();
    assert_eq!(img.data.len(), 1);
    assert_eq!(img.get_pixel(0, 0), consts::BLACK);

    let _ = img.save("test/1bb-1x1.bmp");
    let img = open("test/1bb-1x1.bmp").unwrap();
    assert_eq!(img.data.len(), 1);
    assert_eq!(img.get_pixel(0, 0), consts::BLACK);
}

#[test]
fn read_write_4pbb_bmp_image() {
    let img = open("test/bmptestsuite-0.9/valid/4bpp-1x1.bmp").unwrap_or_else(|e| {
        panic!("{}", e);
    });
    assert_eq!(img.data.len(), 1);
    assert_eq!(img.get_pixel(0, 0), consts::BLUE);

    let _ = img.save("test/4bb-1x1.bmp");
    let img = open("test/4bb-1x1.bmp").unwrap_or_else(|e| {
        panic!("{}", e);
    });
    assert_eq!(img.data.len(), 1);
    assert_eq!(img.get_pixel(0, 0), consts::BLUE);
}

#[test]
fn read_write_8pbb_bmp_image() {
    let img = open("test/bmptestsuite-0.9/valid/8bpp-1x1.bmp").unwrap_or_else(|e| {
        panic!("{}", e);
    });
    assert_eq!(img.data.len(), 1);
    assert_eq!(img.get_pixel(0, 0), consts::BLUE);

    let _ = img.save("test/8bb-1x1.bmp");
    let img = open("test/8bb-1x1.bmp").unwrap_or_else(|e| {
        panic!("{}", e);
    });
    assert_eq!(img.data.len(), 1);
    assert_eq!(img.get_pixel(0, 0), consts::BLUE);
}

#[test]
fn error_when_opening_unexisting_image() {
    let result = open("test/no_img.bmp");
    match result {
        Err(BmpError{ kind: BmpErrorKind::BmpIoError(_), .. }) => (/* Expected */),
        _ => panic!("Ghost image!?")
    }
}

#[test]
fn error_when_opening_image_with_wrong_bits_per_pixel() {
    let result = open("test/bmptestsuite-0.9/valid/32bpp-1x1.bmp");
    match result {
        Err(BmpError { kind: BmpErrorKind::UnsupportedBitsPerPixel, .. }) => (/* Expected */),
        _ => panic!("32bpp should not be supported")
    }
}

#[test]
fn error_when_opening_image_with_wrong_magic_numbers() {
    let result = open("test/bmptestsuite-0.9/corrupt/magicnumber-bad.bmp");
    match result {
        Err(BmpError { kind: BmpErrorKind::WrongMagicNumbers, .. }) => (/* Expected */),
        _ => panic!("Wrong magic numbers should not be supported")
    }
}

#[test]
fn can_create_bmp_file() {
    let mut bmp = Image::new(2, 2);
    bmp.set_pixel(0, 0, consts::RED);
    bmp.set_pixel(1, 0, consts::LIME);
    bmp.set_pixel(0, 1, consts::BLUE);
    bmp.set_pixel(1, 1, consts::WHITE);
    let _ = bmp.save("test/rgbw_test.bmp");

    let bmp_img = open("test/rgbw_test.bmp").unwrap();
    assert_eq!(bmp_img.get_pixel(0, 0), consts::RED);
    assert_eq!(bmp_img.get_pixel(1, 0), consts::LIME);
    assert_eq!(bmp_img.get_pixel(0, 1), consts::BLUE);
    assert_eq!(bmp_img.get_pixel(1, 1), consts::WHITE);

    verify_test_bmp_image(bmp_img);
}

#[test]
fn changing_pixels_does_not_push_image_data() {
    let mut img = Image::new(2, 1);
    img.set_pixel(1, 0, consts::WHITE);
    img.set_pixel(0, 0, consts::WHITE);

    assert_eq!(img.get_pixel(0, 0), consts::WHITE);
    assert_eq!(img.get_pixel(1, 0), consts::WHITE);
}

#[test]
fn coordinates_iterator_gives_x_and_y_in_row_major_order() {
    let img = Image::new(2, 3);
    let mut coords = img.coordinates();
    assert_eq!(coords.next(), Some((0, 0)));
    assert_eq!(coords.next(), Some((1, 0)));
    assert_eq!(coords.next(), Some((0, 1)));
    assert_eq!(coords.next(), Some((1, 1)));
    assert_eq!(coords.next(), Some((0, 2)));
    assert_eq!(coords.next(), Some((1, 2)));
}

#[bench]
fn write_bmp(b: &mut test::Bencher) {
    let img = Image::new(320, 240);
    b.iter(|| img.save("test/bench_test.bmp"));
}

#[bench]
fn open_bmp(b: &mut test::Bencher) {
    b.iter(|| open("test/bmptestsuite-0.9/valid/24bpp-320x240.bmp"));
}
<|endoftext|>


<commit_before>use regex::Regex;

//

 to "\n text \n", seems as well that there might be just
 defined without closing tag
// link to single link
// remove other tags for now like

pub enum FormatType {
    Paragraph,
    Link,
    Other,
}

fn replace_paragraphs(s: String) -> String {
    // todo split
    let mut r = replace_paragraphs_opening_tags(&s);
    r = replace_paragraphs_closing_tags(&r);
    r
}

fn replace_paragraphs_closing_tags(s: &str) -> String {
    let closing_tags_with_whitespace = Regex::new(r"(\s*
\s*)").unwrap();
    closing_tags_with_whitespace.replace_all(s, "").into_owned()
}

fn replace_paragraphs_opening_tags(s: &str) -> String {
    let opening_tags_with_whitespace = Regex::new(r"(\s*
\s*)").unwrap();
    opening_tags_with_whitespace.replace_all(s, "\n").into_owned()
}

fn remove_double_links(s: String) -> String {
    "".to_owned()
}

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

    #[test]
    fn test_replace_paragraphs() {
        let mut s: String = format!("aaaaaa zzz zzaaa

");
        s = replace_paragraphs(s);
        assert!(!s.contains("
"));
        assert!(!s.contains("
"));
        assert_eq!("aaaaaa zzz zzaaa", s);

    }
}<commit_msg>link formatting and fixed some bugs in regex<commit_after>use regex::Regex;

//

 to "\n text \n", seems as well that there might be just
 defined without closing tag
// link to single link
// remove other tags for now like

pub enum FormatType {
    Paragraph,
    Link,
    Other,
}

fn replace_paragraphs(s: String) -> String {
    // todo split
    let mut r = replace_paragraphs_opening_tags(&s);
    r = replace_paragraphs_closing_tags(&r);
    r
}

fn replace_paragraphs_closing_tags(s: &str) -> String {
    let re = Regex::new(r"( *
 *)").unwrap();
    re.replace_all(s, "").into_owned()
}

fn replace_paragraphs_opening_tags(s: &str) -> String {
    let re = Regex::new(r"( *
 *)").unwrap();
    re.replace_all(s, "\n").into_owned()
}

fn replace_link_opening_tags(s: &str) -> String {
    let re = Regex::new(r"( *)").unwrap();
    re.replace_all(s, "").into_owned()
}

fn replace_link_closing_tags(s: &str) -> String {
    let re = Regex::new(r"( * *)").unwrap();
    re.replace_all(s, "").into_owned()
}

fn replace_links(s: String) -> String {
    let mut r = replace_link_opening_tags(&s);
    r = replace_link_closing_tags(&r);
    r
}

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

    #[test]
    fn test_replace_paragraphs() {
        let mut s: String = format!("aaaaaa zzz zzaaa

");
        s = replace_paragraphs(s);
        assert_eq!("aaaaaa zzz zzaaa\n", s);

        s = format!("
 para
 ");
        s = replace_paragraphs(s);
        assert_eq!("\npara", s);
    }

    #[test]
    fn test_replace_links() {
        let mut s: String = format!("this is  \
                                     http://www.link.com ");
        s = replace_links(s);
        assert_eq!("this is http://www.link.com", s);
    }

}<|endoftext|>


<commit_before>use rusticata_macros::newtype_enum;

/// TLS alert severity
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct TlsAlertSeverity(pub u8);

newtype_enum! {
impl display TlsAlertSeverity {
    Warning = 0x01,
    Fatal   = 0x02
}
}

/// TLS alert description
///
/// Alerts are defined in the [IANA TLS Alert
/// Registry](https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml#tls-parameters-6)
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct TlsAlertDescription(pub u8);

newtype_enum! {
impl display TlsAlertDescription {
    CloseNotify            = 0x00,
    EndOfEarlyData         = 0x01,
    UnexpectedMessage      = 0x0A,
    BadRecordMac           = 0x14,
    DecryptionFailed       = 0x15,
    RecordOverflow         = 0x16,
    DecompressionFailure   = 0x1E,
    HandshakeFailure       = 0x28,
    NoCertificate          = 0x29,
    BadCertificate         = 0x2A,
    UnsupportedCertificate = 0x2B,
    CertificateRevoked     = 0x2C,
    CertificateExpired     = 0x2D,
    CertificateUnknown     = 0x2E,
    IllegalParameter       = 0x2F,
    UnknownCa              = 0x30,
    AccessDenied           = 0x31,
    DecodeError            = 0x32,
    DecryptError           = 0x33,
    ExportRestriction      = 0x3C,
    ProtocolVersion        = 0x46,
    InsufficientSecurity   = 0x47,
    InternalError          = 0x50,
    InappropriateFallback  = 0x56,
    UserCancelled          = 0x5A,
    NoRenegotiation        = 0x64,
    MissingExtension       = 0x6d,
    UnsupportedExtension   = 0x6e,
    CertUnobtainable       = 0x6f,
    UnrecognizedName       = 0x70,
    BadCertStatusResponse  = 0x71,
    BadCertHashValue       = 0x72,
    UnknownPskIdentity     = 0x73,
    CertificateRequired    = 0x74,
    NoApplicationProtocol  = 0x78 // [RFC7301]
}
}

/// TLS alert message
#[derive(Clone, PartialEq)]
pub struct TlsMessageAlert {
    /// Should match a [TlsAlertSeverity](enum.TlsAlertSeverity.html) value
    pub severity: TlsAlertSeverity,
    /// Should match a [TlsAlertDescription](enum.TlsAlertDescription.html) value
    pub code: TlsAlertDescription,
}

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

    #[test]
    fn test_tlsalert_cast_severity() {
        let a = TlsAlertSeverity::Warning;

        let a_u8 = a.0;
        assert_eq!(a_u8, 0x01);

        let b = TlsAlertSeverity(a_u8);
        assert_eq!(b, TlsAlertSeverity::Warning);

        let s = format!("{}", b);
        assert_eq!(s, "Warning");

        let s = format!("{}", TlsAlertSeverity(129));
        assert_eq!(s, "TlsAlertSeverity(129 / 0x81)");
    }

    #[test]
    fn test_tlsalert_cast_description() {
        let a = TlsAlertDescription::HandshakeFailure;

        let a_u8 = a.0;
        assert_eq!(a_u8, 0x28);

        let b = TlsAlertDescription(a_u8);
        assert_eq!(b, TlsAlertDescription::HandshakeFailure);
    }
} // mod tests
<commit_msg>`EndOfEarlyData` is a TLS HandshakeType, not a AlertDescription (Closes #10)<commit_after>use rusticata_macros::newtype_enum;

/// TLS alert severity
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct TlsAlertSeverity(pub u8);

newtype_enum! {
impl display TlsAlertSeverity {
    Warning = 0x01,
    Fatal   = 0x02
}
}

/// TLS alert description
///
/// Alerts are defined in the [IANA TLS Alert
/// Registry](https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml#tls-parameters-6)
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct TlsAlertDescription(pub u8);

newtype_enum! {
impl display TlsAlertDescription {
    CloseNotify            = 0x00,
    UnexpectedMessage      = 0x0A,
    BadRecordMac           = 0x14,
    DecryptionFailed       = 0x15,
    RecordOverflow         = 0x16,
    DecompressionFailure   = 0x1E,
    HandshakeFailure       = 0x28,
    NoCertificate          = 0x29,
    BadCertificate         = 0x2A,
    UnsupportedCertificate = 0x2B,
    CertificateRevoked     = 0x2C,
    CertificateExpired     = 0x2D,
    CertificateUnknown     = 0x2E,
    IllegalParameter       = 0x2F,
    UnknownCa              = 0x30,
    AccessDenied           = 0x31,
    DecodeError            = 0x32,
    DecryptError           = 0x33,
    ExportRestriction      = 0x3C,
    ProtocolVersion        = 0x46,
    InsufficientSecurity   = 0x47,
    InternalError          = 0x50,
    InappropriateFallback  = 0x56,
    UserCancelled          = 0x5A,
    NoRenegotiation        = 0x64,
    MissingExtension       = 0x6d,
    UnsupportedExtension   = 0x6e,
    CertUnobtainable       = 0x6f,
    UnrecognizedName       = 0x70,
    BadCertStatusResponse  = 0x71,
    BadCertHashValue       = 0x72,
    UnknownPskIdentity     = 0x73,
    CertificateRequired    = 0x74,
    NoApplicationProtocol  = 0x78 // [RFC7301]
}
}

/// TLS alert message
#[derive(Clone, PartialEq)]
pub struct TlsMessageAlert {
    /// Should match a [TlsAlertSeverity](enum.TlsAlertSeverity.html) value
    pub severity: TlsAlertSeverity,
    /// Should match a [TlsAlertDescription](enum.TlsAlertDescription.html) value
    pub code: TlsAlertDescription,
}

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

    #[test]
    fn test_tlsalert_cast_severity() {
        let a = TlsAlertSeverity::Warning;

        let a_u8 = a.0;
        assert_eq!(a_u8, 0x01);

        let b = TlsAlertSeverity(a_u8);
        assert_eq!(b, TlsAlertSeverity::Warning);

        let s = format!("{}", b);
        assert_eq!(s, "Warning");

        let s = format!("{}", TlsAlertSeverity(129));
        assert_eq!(s, "TlsAlertSeverity(129 / 0x81)");
    }

    #[test]
    fn test_tlsalert_cast_description() {
        let a = TlsAlertDescription::HandshakeFailure;

        let a_u8 = a.0;
        assert_eq!(a_u8, 0x28);

        let b = TlsAlertDescription(a_u8);
        assert_eq!(b, TlsAlertDescription::HandshakeFailure);
    }
} // mod tests
<|endoftext|>


<commit_before>use std::iter::Iterator;
use std::collections::HashSet;

use token::Token;
use scanner::Scanner;

lazy_static! {
    static ref SYMBOL_CHARS: HashSet<char> = vec![
        'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
        'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x',
        'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
        'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V',
        'W', 'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7',
        '8', '9', '-', '_', '$', '^', '&', '*', '!', '@', '%', '+',
        '?', '<', '>', '.', ':', '/', '|', '~', ',', '='
    ].into_iter().collect();
}

pub struct Tokenizer {
    scanner: Scanner,
    reached_eof: bool,
}

impl Tokenizer {
    pub fn new(scanner: Scanner) -> Tokenizer {
        Tokenizer {
            scanner: scanner,
            reached_eof: false,
        }
    }
}

impl Iterator for Tokenizer {
    type Item = Token;

    fn next(&mut self) -> Option<Token> {
        None
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use token::Token;
    use token::Token::*;
    use scanner::Scanner;

    #[test]
    fn backslash() {
        let mut tokenizer = tokenizer_for("\\");
        assert!(tokenizer.next().unwrap() == Backslash);
        assert!(tokenizer.next().is_none());
    }

    #[test]
    fn equals() {
        let mut tokenizer = tokenizer_for("=");
        assert!(tokenizer.next().unwrap() == Equals);
        assert!(tokenizer.next().is_none());
    }

    #[test]
    fn parenOpen() {
        let mut tokenizer = tokenizer_for("(");
        assert!(tokenizer.next().unwrap() == ParenOpen);
        assert!(tokenizer.next().is_none());
    }

    #[test]
    fn parenClose() {
        let mut tokenizer = tokenizer_for(")");
        assert!(tokenizer.next().unwrap() == ParenClose);
        assert!(tokenizer.next().is_none());
    }

    #[test]
    fn eol() {
        let mut tokenizer = tokenizer_for("\n");
        assert!(tokenizer.next().unwrap() == EOL);
        assert!(tokenizer.next().is_none());
    }

    #[test]
    fn recognizes_multiple_tokens_separated_by_whitespace() {
        let mut tokenizer = tokenizer_for("\\ ) \n ( \\ = = )");
        let expected = [Backslash, ParenClose, EOL, ParenOpen, Backslash, Equals, Equals, ParenClose];

        for token in expected.into_iter() {
            assert!(tokenizer.next().unwrap() == *token);
        }

        assert!(tokenizer.next().is_none());
    }

    #[test]
    fn groups_characters_into_symbols() {
        let symbol = "abqq$$1111^&/|!";
        let mut tokenizer = tokenizer_for(symbol);
        assert!(tokenizer.next().unwrap() == Symbol(symbol.to_owned()));
        assert!(tokenizer.next().is_none());
    }

    #[test]
    fn groups_equals_into_symbols_when_there_is_no_whitespace() {
        let symbol = "=ifsaoi=hfsdMMDS,,,,~~~:=".to_owned();

        // Make sure leading whitespace does not effect the output
        let mut tokenizer = tokenizer_for(format!("  {}", symbol).as_ref());

        assert!(tokenizer.next().unwrap() == Symbol(symbol));
        assert!(tokenizer.next().is_none());
    }

    #[test]
    fn disallows_symbols_starting_with_numbers() {
    }

    #[test]
    fn accepts_all_valid_symbol_characters_into_a_symbol() {
    }

    #[test]
    fn recognizes_parenthesis_regardless_of_whitespace() {
    }

    #[test]
    fn ignores_leading_whitespace() {
    }

    fn tokenizer_for(string: &str) -> Tokenizer {
        Tokenizer::new(Scanner::from_str(string))
    }
}

<commit_msg>Wrapping Token in a Result to model errors<commit_after>use std::iter::Iterator;
use std::result;
use std::collections::HashSet;

use token::Token;
use scanner::Scanner;

lazy_static! {
    static ref SYMBOL_CHARS: HashSet<char> = vec![
        'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
        'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x',
        'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
        'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V',
        'W', 'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7',
        '8', '9', '-', '_', '$', '^', '&', '*', '!', '@', '%', '+',
        '?', '<', '>', '.', ':', '/', '|', '~', ',', '='
    ].into_iter().collect();
}

pub type TokenResult = result::Result<Token, String>;

pub struct Tokenizer {
    scanner: Scanner,
    reached_eof: bool,
}

impl Tokenizer {
    pub fn new(scanner: Scanner) -> Tokenizer {
        Tokenizer {
            scanner: scanner,
            reached_eof: false,
        }
    }
}

impl Iterator for Tokenizer {
    type Item = TokenResult;

    fn next(&mut self) -> Option<Self::Item> {
        None
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use token::Token::*;
    use scanner::Scanner;

    #[test]
    fn backslash() {
        let mut tokenizer = tokenizer_for("\\");
        assert!(tokenizer.next().unwrap().unwrap() == Backslash);
        assert!(tokenizer.next().is_none());
    }

    #[test]
    fn equals() {
        let mut tokenizer = tokenizer_for("=");
        assert!(tokenizer.next().unwrap().unwrap() == Equals);
        assert!(tokenizer.next().is_none());
    }

    #[test]
    fn paren_open() {
        let mut tokenizer = tokenizer_for("(");
        assert!(tokenizer.next().unwrap().unwrap() == ParenOpen);
        assert!(tokenizer.next().is_none());
    }

    #[test]
    fn paren_close() {
        let mut tokenizer = tokenizer_for(")");
        assert!(tokenizer.next().unwrap().unwrap() == ParenClose);
        assert!(tokenizer.next().is_none());
    }

    #[test]
    fn eol() {
        let mut tokenizer = tokenizer_for("\n");
        assert!(tokenizer.next().unwrap().unwrap() == EOL);
        assert!(tokenizer.next().is_none());
    }

    #[test]
    fn recognizes_multiple_tokens_separated_by_whitespace() {
        let mut tokenizer = tokenizer_for("\\ ) \n ( \\ = = )");
        let expected = [Backslash, ParenClose, EOL, ParenOpen, Backslash, Equals, Equals, ParenClose];

        for token in expected.into_iter() {
            assert!(tokenizer.next().unwrap().unwrap() == *token);
        }

        assert!(tokenizer.next().is_none());
    }

    #[test]
    fn groups_characters_into_symbols() {
        let symbol = "abqq$$1111^&/|!";
        let mut tokenizer = tokenizer_for(symbol);
        assert!(tokenizer.next().unwrap().unwrap() == Symbol(symbol.to_owned()));
        assert!(tokenizer.next().is_none());
    }

    #[test]
    fn groups_equals_into_symbols_when_there_is_no_whitespace() {
        let symbol = "=ifsaoi=hfsdMMDS,,,,~~~:=".to_owned();

        // Make sure leading whitespace does not effect the output
        let mut tokenizer = tokenizer_for(format!("  {}", symbol).as_ref());

        assert!(tokenizer.next().unwrap().unwrap() == Symbol(symbol));
        assert!(tokenizer.next().is_none());
    }

    #[test]
    fn disallows_symbols_starting_with_numbers() {
    }

    #[test]
    fn accepts_all_valid_symbol_characters_into_a_symbol() {
    }

    #[test]
    fn recognizes_parenthesis_regardless_of_whitespace() {
    }

    #[test]
    fn ignores_leading_whitespace() {
    }

    fn tokenizer_for(string: &str) -> Tokenizer {
        Tokenizer::new(Scanner::from_str(string))
    }
}

<|endoftext|>


<commit_before>/**
Katy Williamson kcw4sn
Ben Terner bt3ze
@virginia.edu

Final Project for CS4414 - Operating Systems
A parallel MST implementation on images in Rust

*/

/*
some documentation:
Pixel object is composed of r,g,b values, a color, and an x,y index that takes the place of its adjacency list
Point is just an (x,y) value to denote a pixel's location
Edge contains two points: source and dest, along with the edge cost between them

*/

extern mod extra;
use std::{os, num,hashmap} ;
use extra::{arc,priority_queue};

struct Pixel{
    r: int,
    b: int,
    g: int,
    color: int,
    x: int,
    y: int
}

impl Pixel {
    fn new(red: int, blue: int, green: int, x: int, y: int) -> Pixel {
        Pixel{
            r: red,
            b: blue,
            g: green,
            color: -1,
            x: x,
            y: y
        }
    }
}

struct Point {
    x: int,
    y: int
}

impl Point{
    fn new(x: int, y: int)-> Point {
        Point {
            x: x,
            y: y
        }
    }
}

struct Edge {
    source: Point,
    dest: Point,
    cost: float
}

impl Edge {
    fn new(s: Point, d: Point, cost: float) -> Edge {
        Edge {
            source: s,
            dest: d,
            cost: cost
        }
    }
}

impl Ord for Edge {
    fn lt(&self, other: &Edge) -> bool {
        self.cost < other.cost
    }
}

fn edgeCost(a: &Pixel, b: &Pixel) -> float {
    num::sqrt( (
            a.r*a.r-b.r*b.r + a.g*a.g-b.g*b.g + a.b*a.b-b.b*b.b ) as float)
}

fn readImage( filename: &~str) -> ~ [ ~[Pixel]] {
    ~[~[]]
}

fn main(){
    let argv =  os::args();
    println(argv.to_str());
    let length = match from_str::<int>(argv[2]) {
        Some(x) => x,
        None() => 0
    };
    let width = match from_str::<int>(argv[3]) {
        Some(x) => x,
        None() => 0
    };

    let pixels: ~[ ~[Pixel] ] = readImage(&argv[1]);
    let mut find_arcs: ~[ ~[arc::RWArc<Pixel>] ] =  ~[ ~[]];
    let mut len = 0;
    let mut wid = 0;
    loop {
        loop {
            find_arcs[len][wid] = arc::RWArc::new(pixels[len][wid]);
                wid+=1;
            if(wid == width) {
                wid = 0;
                break;
            }
        }
        len+=1;
        if(len == length) {
            break;
        }
    }

    let arcs = find_arcs; // now we have an immutable array that can be shared

// split into threads here

    let mut x= 0;
    let mut y= 0;

    let mut queue: priority_queue::PriorityQueue<Edge> =  priority_queue::PriorityQueue::new();
    let mut visited: hashmap::HashMap<(int,int),bool> = hashmap::HashMap::new();

    let mut newvisit: bool = true;

    loop { // iterate through items in the queue, which contains all of the edges/vertices
        if(newvisit){
            let neighbors = [ (x,y-1),(x+1,y), (x,y+1), (x,y-1)];
            for &coord in neighbors.iter() {
                let (w,z) = coord;
                if w >=0 && w < width && z >=0 && z <= length { // bounds checking
                    // if neighbor at coord has not been or colored
                    if pixels[w][z].color < 0 { // then we have a new vertex
                        queue.push( Edge::new(Point::new(x,y),Point::new(w,z),edgeCost(&pixels[x][y],&pixels[w][z])));
                    }
                }
            }
        }

        let edge = queue.maybe_pop();
        match edge {
            Some(e) => {
                let mut col = 0;
                do arcs[e.dest.x][e.dest.y].read |dest| {
                    col = dest.color;
                }
                if col < 0 {
                    // not in any tree
                    let coord = (e.dest.x,e.dest.y);
                    if *visited.get(&coord) == false { // use visited hashmap to figure out if we're at a new vertex
                        visited.insert(coord,true);
                        x = e.dest.x;
                        y = e.dest.y;
                        newvisit = true;
                    } else {
                        newvisit = false;
                    }

                    // use an arc to write the following
//                    pixels[e.dest.x][e.dest.y].color = pixels[e.source.x][e.source.y].color;
                    do arcs[e.dest.x][e.dest.y].write |dest| {
                        do arcs[e.source.x][e.source.y].read |src| {
                            dest.color = src.color;
                        }
                    }
                }
            }
            None => { break; } // this should really never execute till the end
        }
    }

}
<commit_msg>spawning into threads.<commit_after>/**
Katy Williamson kcw4sn
Ben Terner bt3ze
@virginia.edu

Final Project for CS4414 - Operating Systems
A parallel MST implementation on images in Rust

*/

/*
some documentation:
Pixel object is composed of r,g,b values, a color, and an x,y index that takes the place of its adjacency list
Point is just an (x,y) value to denote a pixel's location
Edge contains two points: source and dest, along with the edge cost between them

*/

extern mod extra;
use std::{os, num,hashmap} ;
use extra::{arc,priority_queue};

struct Pixel{
    r: int,
    b: int,
    g: int,
    color: int,
    x: int,
    y: int
}

impl Pixel {
    fn new(red: int, blue: int, green: int, x: int, y: int) -> Pixel {
        Pixel{
            r: red,
            b: blue,
            g: green,
            color: -1,
            x: x,
            y: y
        }
    }
}

impl Clone for Pixel{
    fn clone(&self) -> Pixel {
        Pixel{
            r: self.r,
            b: self.b,
            g: self.g,
            color: self.color,
            x: self.x,
            y: self.y
        }
    }
}

struct Point {
    x: int,
    y: int
}

impl Point{
    fn new(x: int, y: int)-> Point {
        Point {
            x: x,
            y: y
        }
    }
}

struct Edge {
    source: Point,
    dest: Point,
    cost: float
}

impl Edge {
    fn new(s: Point, d: Point, cost: float) -> Edge {
        Edge {
            source: s,
            dest: d,
            cost: cost
        }
    }
}

impl Ord for Edge {
    fn lt(&self, other: &Edge) -> bool {
        self.cost < other.cost
    }
}

fn edgeCost(a: &Pixel, b: &Pixel) -> float {
    num::sqrt( (
            a.r*a.r-b.r*b.r + a.g*a.g-b.g*b.g + a.b*a.b-b.b*b.b ) as float)
}

fn readImage( filename: &~str) -> ~ [ ~[Pixel]] {
    ~[~[]]
}

fn main(){
    let argv =  os::args();
    println(argv.to_str());

    let pixels: ~[ ~[Pixel] ] = readImage(&argv[1]);

    // width and height should be replaced by just reading them from the file
    let width = match from_str::<int>(argv[2]) {
        Some(x) => x,
        None() => 0
    };
    let height = match from_str::<int>(argv[3]) {
        Some(x) => x,
        None() => 0
    };

    let mut find_arcs: ~[ ~[arc::RWArc<Pixel>] ] =  ~[ ~[]];
    let mut heit = 0;
    let mut wid = 0;
    loop {
        loop {
            find_arcs[heit][wid] = arc::RWArc::new(pixels[heit][wid]);
                wid+=1;
            if(wid == width) {
                wid = 0;
                break;
            }
        }
        heit+=1;
        if(heit == height) {
            break;
        }
    }

    let arcs = find_arcs; // now we have an immutable array that can be shared

    let corners = [ (0,0),(0,width-1),(height-1,0),(height-1,width-1) ];

    for &corner in corners.iter() {
        let (a,b) = corner;
        let shared_arcs = arcs.clone();
        let shared_pixels = pixels.clone();
        do spawn { // split into threads here

            let mut x=a;
            let mut y=b;

            let mut queue: priority_queue::PriorityQueue<Edge> =  priority_queue::PriorityQueue::new();
            let mut visited: hashmap::HashMap<(int,int),bool> = hashmap::HashMap::new();

            let mut newvisit: bool = true;

            loop { // iterate through items in the queue, which contains all of the edges/vertices
                if(newvisit){
                    let neighbors = [ (x,y-1),(x+1,y), (x,y+1), (x,y-1)];
                    for &coord in neighbors.iter() {
                        let (w,z) = coord;
                        if w >=0 && w < width && z >=0 && z < height { // bounds checking
                            // if neighbor at coord has not been or colored
                            let mut col = 0;
                            do shared_arcs[w][z].read |edg| {
                                col = edg.color;
                            }
                            if col < 0 { // then we have a new vertex
                                queue.push( Edge::new(Point::new(x,y),Point::new(w,z),edgeCost(&shared_pixels[x][y],&shared_pixels[w][z])));
                            }
                        }
                    }
                }

                let edge = queue.maybe_pop();
                match edge {
                Some(e) => {
                        let mut col = 0;
                        do shared_arcs[e.dest.x][e.dest.y].read |dest| {
                        col = dest.color;
                        }
                        if col < 0 {
                            // not in any tree
                            let coord = (e.dest.x,e.dest.y);
                            if *visited.get(&coord) == false { // use visited hashmap to figure out if we're at a new vertex
                                visited.insert(coord,true);
                                x = e.dest.x;
                                y = e.dest.y;
                            newvisit = true;
                            } else {
                                newvisit = false;
                            }

                            // use an arc to write the following
                            //                    pixels[e.dest.x][e.dest.y].color = pixels[e.source.x][e.source.y].color;
                            do shared_arcs[e.dest.x][e.dest.y].write |dest| {
                                do shared_arcs[e.source.x][e.source.y].read |src| {
                                    dest.color = src.color;
                                }
                            }
                        }
                    }
                    None => { break; } // this should execute at the end when there are no more unvisited or uncolored nodes for a thread
                }
            }
        }
    }
}
<|endoftext|>


<commit_before>use rustc::lint::*;
use rustc::hir::def_id::DefId;
use rustc::ty;
use rustc::hir::*;
use syntax::ast::{Lit, LitKind, Name};
use syntax::codemap::{Span, Spanned};
use syntax::ptr::P;
use utils::{get_item_name, in_macro, snippet, span_lint, span_lint_and_then, walk_ptrs_ty};

/// **What it does:** Checks for getting the length of something via `.len()`
/// just to compare to zero, and suggests using `.is_empty()` where applicable.
///
/// **Why is this bad?** Some structures can answer `.is_empty()` much faster
/// than calculating their length. So it is good to get into the habit of using
/// `.is_empty()`, and having it is cheap. Besides, it makes the intent clearer
/// than a comparison.
///
/// **Known problems:** None.
///
/// **Example:**
/// ```rust
/// if x.len() == 0 { .. }
/// ```
declare_lint! {
    pub LEN_ZERO,
    Warn,
    "checking `.len() == 0` or `.len() > 0` (or similar) when `.is_empty()` \
     could be used instead"
}

/// **What it does:** Checks for items that implement `.len()` but not
/// `.is_empty()`.
///
/// **Why is this bad?** It is good custom to have both methods, because for
/// some data structures, asking about the length will be a costly operation,
/// whereas `.is_empty()` can usually answer in constant time. Also it used to
/// lead to false positives on the [`len_zero`](#len_zero) lint – currently that
/// lint will ignore such entities.
///
/// **Known problems:** None.
///
/// **Example:**
/// ```rust
/// impl X {
///     pub fn len(&self) -> usize { .. }
/// }
/// ```
declare_lint! {
    pub LEN_WITHOUT_IS_EMPTY,
    Warn,
    "traits or impls with a public `len` method but no corresponding `is_empty` method"
}

#[derive(Copy,Clone)]
pub struct LenZero;

impl LintPass for LenZero {
    fn get_lints(&self) -> LintArray {
        lint_array!(LEN_ZERO, LEN_WITHOUT_IS_EMPTY)
    }
}

impl LateLintPass for LenZero {
    fn check_item(&mut self, cx: &LateContext, item: &Item) {
        if in_macro(cx, item.span) {
            return;
        }

        match item.node {
            ItemTrait(_, _, _, ref trait_items) => check_trait_items(cx, item, trait_items),
            ItemImpl(_, _, _, None, _, ref impl_items) => check_impl_items(cx, item, impl_items),
            _ => (),
        }
    }

    fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
        if in_macro(cx, expr.span) {
            return;
        }

        if let ExprBinary(Spanned { node: cmp, .. }, ref left, ref right) = expr.node {
            match cmp {
                BiEq => check_cmp(cx, expr.span, left, right, ""),
                BiGt | BiNe => check_cmp(cx, expr.span, left, right, "!"),
                _ => (),
            }
        }
    }
}

fn check_trait_items(cx: &LateContext, item: &Item, trait_items: &[TraitItem]) {
    fn is_named_self(item: &TraitItem, name: &str) -> bool {
        item.name.as_str() == name &&
        if let MethodTraitItem(ref sig, _) = item.node {
            is_self_sig(sig)
        } else {
            false
        }
    }

    if !trait_items.iter().any(|i| is_named_self(i, "is_empty")) {
        if let Some(i) = trait_items.iter().find(|i| is_named_self(i, "len")) {
            if cx.access_levels.is_exported(i.id) {
                span_lint(cx,
                          LEN_WITHOUT_IS_EMPTY,
                          i.span,
                          &format!("trait `{}` has a `len` method but no `is_empty` method",
                                   item.name));
            }
        }
    }
}

fn check_impl_items(cx: &LateContext, item: &Item, impl_items: &[ImplItem]) {
    fn is_named_self(item: &ImplItem, name: &str) -> bool {
        item.name.as_str() == name &&
        if let ImplItemKind::Method(ref sig, _) = item.node {
            is_self_sig(sig)
        } else {
            false
        }
    }

    let is_empty = if let Some(is_empty) = impl_items.iter().find(|i| is_named_self(i, "is_empty")) {
        if cx.access_levels.is_exported(is_empty.id) {
            return;
        } else {
            "a private"
        }
    } else {
        "no corresponding"
    };

    if let Some(i) = impl_items.iter().find(|i| is_named_self(i, "len")) {
        if cx.access_levels.is_exported(i.id) {
            let def_id = cx.tcx.map.local_def_id(item.id);
            let ty = cx.tcx.item_type(def_id);

            span_lint(cx,
                      LEN_WITHOUT_IS_EMPTY,
                      i.span,
                      &format!("item `{}` has a public `len` method but {} `is_empty` method",
                               ty,
                               is_empty));
        }
    }
}

fn is_self_sig(sig: &MethodSig) -> bool {
    if sig.decl.has_self() {
        sig.decl.inputs.len() == 1
    } else {
        false
    }
}

fn check_cmp(cx: &LateContext, span: Span, left: &Expr, right: &Expr, op: &str) {
    // check if we are in an is_empty() method
    if let Some(name) = get_item_name(cx, left) {
        if name.as_str() == "is_empty" {
            return;
        }
    }
    match (&left.node, &right.node) {
        (&ExprLit(ref lit), &ExprMethodCall(ref method, _, ref args)) |
        (&ExprMethodCall(ref method, _, ref args), &ExprLit(ref lit)) => {
            check_len_zero(cx, span, &method.node, args, lit, op)
        }
        _ => (),
    }
}

fn check_len_zero(cx: &LateContext, span: Span, name: &Name, args: &[P<Expr>], lit: &Lit, op: &str) {
    if let Spanned { node: LitKind::Int(0, _), .. } = *lit {
        if name.as_str() == "len" && args.len() == 1 && has_is_empty(cx, &args[0]) {
            span_lint_and_then(cx, LEN_ZERO, span, "length comparison to zero", |db| {
                db.span_suggestion(span,
                                   "consider using `is_empty`",
                                   format!("{}{}.is_empty()", op, snippet(cx, args[0].span, "_")));
            });
        }
    }
}

/// Check if this type has an `is_empty` method.
fn has_is_empty(cx: &LateContext, expr: &Expr) -> bool {
    /// Get an `AssociatedItem` and return true if it matches `is_empty(self)`.
    fn is_is_empty(cx: &LateContext, item: &ty::AssociatedItem) -> bool {
        if let ty::AssociatedKind::Method = item.kind {
            if item.name.as_str() == "is_empty" {
                let ty = cx.tcx.item_type(item.def_id).fn_sig().skip_binder();
                ty.inputs.len() == 1
            } else {
                false
            }
        } else {
            false
        }
    }

    /// Check the inherent impl's items for an `is_empty(self)` method.
    fn has_is_empty_impl(cx: &LateContext, id: DefId) -> bool {
        cx.tcx.inherent_impls.borrow().get(&id).map_or(false, |impls| impls.iter().any(|imp| {
            cx.tcx.associated_items(*imp).any(|item| {
                is_is_empty(cx, &item)
            })
        }))
    }

    let ty = &walk_ptrs_ty(cx.tcx.tables().expr_ty(expr));
    match ty.sty {
        ty::TyTrait(_) => {
            cx.tcx
              .associated_items(ty.ty_to_def_id().expect("trait impl not found"))
              .any(|item| is_is_empty(cx, &item))
        }
        ty::TyProjection(_) => ty.ty_to_def_id().map_or(false, |id| has_is_empty_impl(cx, id)),
        ty::TyAdt(id, _) => has_is_empty_impl(cx, id.did),
        ty::TyArray(..) | ty::TyStr => true,
        _ => false,
    }
}
<commit_msg>Rustup to *rustc 1.15.0-nightly (ac635aa95 2016-11-18)*<commit_after>use rustc::lint::*;
use rustc::hir::def_id::DefId;
use rustc::ty;
use rustc::hir::*;
use syntax::ast::{Lit, LitKind, Name};
use syntax::codemap::{Span, Spanned};
use syntax::ptr::P;
use utils::{get_item_name, in_macro, snippet, span_lint, span_lint_and_then, walk_ptrs_ty};

/// **What it does:** Checks for getting the length of something via `.len()`
/// just to compare to zero, and suggests using `.is_empty()` where applicable.
///
/// **Why is this bad?** Some structures can answer `.is_empty()` much faster
/// than calculating their length. So it is good to get into the habit of using
/// `.is_empty()`, and having it is cheap. Besides, it makes the intent clearer
/// than a comparison.
///
/// **Known problems:** None.
///
/// **Example:**
/// ```rust
/// if x.len() == 0 { .. }
/// ```
declare_lint! {
    pub LEN_ZERO,
    Warn,
    "checking `.len() == 0` or `.len() > 0` (or similar) when `.is_empty()` \
     could be used instead"
}

/// **What it does:** Checks for items that implement `.len()` but not
/// `.is_empty()`.
///
/// **Why is this bad?** It is good custom to have both methods, because for
/// some data structures, asking about the length will be a costly operation,
/// whereas `.is_empty()` can usually answer in constant time. Also it used to
/// lead to false positives on the [`len_zero`](#len_zero) lint – currently that
/// lint will ignore such entities.
///
/// **Known problems:** None.
///
/// **Example:**
/// ```rust
/// impl X {
///     pub fn len(&self) -> usize { .. }
/// }
/// ```
declare_lint! {
    pub LEN_WITHOUT_IS_EMPTY,
    Warn,
    "traits or impls with a public `len` method but no corresponding `is_empty` method"
}

#[derive(Copy,Clone)]
pub struct LenZero;

impl LintPass for LenZero {
    fn get_lints(&self) -> LintArray {
        lint_array!(LEN_ZERO, LEN_WITHOUT_IS_EMPTY)
    }
}

impl LateLintPass for LenZero {
    fn check_item(&mut self, cx: &LateContext, item: &Item) {
        if in_macro(cx, item.span) {
            return;
        }

        match item.node {
            ItemTrait(_, _, _, ref trait_items) => check_trait_items(cx, item, trait_items),
            ItemImpl(_, _, _, None, _, ref impl_items) => check_impl_items(cx, item, impl_items),
            _ => (),
        }
    }

    fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
        if in_macro(cx, expr.span) {
            return;
        }

        if let ExprBinary(Spanned { node: cmp, .. }, ref left, ref right) = expr.node {
            match cmp {
                BiEq => check_cmp(cx, expr.span, left, right, ""),
                BiGt | BiNe => check_cmp(cx, expr.span, left, right, "!"),
                _ => (),
            }
        }
    }
}

fn check_trait_items(cx: &LateContext, item: &Item, trait_items: &[TraitItem]) {
    fn is_named_self(item: &TraitItem, name: &str) -> bool {
        item.name.as_str() == name &&
        if let MethodTraitItem(ref sig, _) = item.node {
            if sig.decl.has_self() {
                sig.decl.inputs.len() == 1
            } else {
                false
            }
        } else {
            false
        }
    }

    if !trait_items.iter().any(|i| is_named_self(i, "is_empty")) {
        if let Some(i) = trait_items.iter().find(|i| is_named_self(i, "len")) {
            if cx.access_levels.is_exported(i.id) {
                span_lint(cx,
                          LEN_WITHOUT_IS_EMPTY,
                          i.span,
                          &format!("trait `{}` has a `len` method but no `is_empty` method",
                                   item.name));
            }
        }
    }
}

fn check_impl_items(cx: &LateContext, item: &Item, impl_items: &[ImplItemRef]) {
    fn is_named_self(cx: &LateContext, item: &ImplItemRef, name: &str) -> bool {
        item.name.as_str() == name &&
        if let AssociatedItemKind::Method { has_self } = item.kind {
            has_self && {
                let did = cx.tcx.map.local_def_id(item.id.node_id);
                let impl_ty = cx.tcx.item_type(did);
                impl_ty.fn_args().skip_binder().len() == 1
            }
        } else {
            false
        }
    }

    let is_empty = if let Some(is_empty) = impl_items.iter().find(|i| is_named_self(cx, i, "is_empty")) {
        if cx.access_levels.is_exported(is_empty.id.node_id) {
            return;
        } else {
            "a private"
        }
    } else {
        "no corresponding"
    };

    if let Some(i) = impl_items.iter().find(|i| is_named_self(cx, i, "len")) {
        if cx.access_levels.is_exported(i.id.node_id) {
            let def_id = cx.tcx.map.local_def_id(item.id);
            let ty = cx.tcx.item_type(def_id);

            span_lint(cx,
                      LEN_WITHOUT_IS_EMPTY,
                      i.span,
                      &format!("item `{}` has a public `len` method but {} `is_empty` method",
                               ty,
                               is_empty));
        }
    }
}

fn check_cmp(cx: &LateContext, span: Span, left: &Expr, right: &Expr, op: &str) {
    // check if we are in an is_empty() method
    if let Some(name) = get_item_name(cx, left) {
        if name.as_str() == "is_empty" {
            return;
        }
    }
    match (&left.node, &right.node) {
        (&ExprLit(ref lit), &ExprMethodCall(ref method, _, ref args)) |
        (&ExprMethodCall(ref method, _, ref args), &ExprLit(ref lit)) => {
            check_len_zero(cx, span, &method.node, args, lit, op)
        }
        _ => (),
    }
}

fn check_len_zero(cx: &LateContext, span: Span, name: &Name, args: &[P<Expr>], lit: &Lit, op: &str) {
    if let Spanned { node: LitKind::Int(0, _), .. } = *lit {
        if name.as_str() == "len" && args.len() == 1 && has_is_empty(cx, &args[0]) {
            span_lint_and_then(cx, LEN_ZERO, span, "length comparison to zero", |db| {
                db.span_suggestion(span,
                                   "consider using `is_empty`",
                                   format!("{}{}.is_empty()", op, snippet(cx, args[0].span, "_")));
            });
        }
    }
}

/// Check if this type has an `is_empty` method.
fn has_is_empty(cx: &LateContext, expr: &Expr) -> bool {
    /// Get an `AssociatedItem` and return true if it matches `is_empty(self)`.
    fn is_is_empty(cx: &LateContext, item: &ty::AssociatedItem) -> bool {
        if let ty::AssociatedKind::Method = item.kind {
            if item.name.as_str() == "is_empty" {
                let ty = cx.tcx.item_type(item.def_id).fn_sig().skip_binder();
                ty.inputs.len() == 1
            } else {
                false
            }
        } else {
            false
        }
    }

    /// Check the inherent impl's items for an `is_empty(self)` method.
    fn has_is_empty_impl(cx: &LateContext, id: DefId) -> bool {
        cx.tcx.inherent_impls.borrow().get(&id).map_or(false, |impls| impls.iter().any(|imp| {
            cx.tcx.associated_items(*imp).any(|item| {
                is_is_empty(cx, &item)
            })
        }))
    }

    let ty = &walk_ptrs_ty(cx.tcx.tables().expr_ty(expr));
    match ty.sty {
        ty::TyTrait(_) => {
            cx.tcx
              .associated_items(ty.ty_to_def_id().expect("trait impl not found"))
              .any(|item| is_is_empty(cx, &item))
        }
        ty::TyProjection(_) => ty.ty_to_def_id().map_or(false, |id| has_is_empty_impl(cx, id)),
        ty::TyAdt(id, _) => has_is_empty_impl(cx, id.did),
        ty::TyArray(..) | ty::TyStr => true,
        _ => false,
    }
}
<|endoftext|>


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

//! Operations on tuples

use kinds::Copy;
use vec;

#[cfg(notest)] use cmp::{Eq, Ord};

pub trait CopyableTuple<T, U> {
    fn first(&self) -> T;
    fn second(&self) -> U;
    fn swap(&self) -> (U, T);
}

impl<T:Copy,U:Copy> CopyableTuple<T, U> for (T, U) {

    /// Return the first element of self
    #[inline(always)]
    fn first(&self) -> T {
        let (t, _) = *self;
        return t;
    }

    /// Return the second element of self
    #[inline(always)]
    fn second(&self) -> U {
        let (_, u) = *self;
        return u;
    }

    /// Return the results of swapping the two elements of self
    #[inline(always)]
    fn swap(&self) -> (U, T) {
        let (t, u) = *self;
        return (u, t);
    }

}

pub trait ImmutableTuple<T, U> {
    fn first_ref(&self) -> &'self T;
    fn second_ref(&self) -> &'self U;
}

impl<T, U> ImmutableTuple<T, U> for (T, U) {
    #[inline(always)]
    fn first_ref(&self) -> &'self T {
        match *self {
            (ref t, _) => t,
        }
    }
    #[inline(always)]
    fn second_ref(&self) -> &'self U {
        match *self {
            (_, ref u) => u,
        }
    }
}

pub trait ExtendedTupleOps<A,B> {
    fn zip(&self) -> ~[(A, B)];
    fn map<C>(&self, f: &fn(a: &A, b: &B) -> C) -> ~[C];
}

impl<'self,A:Copy,B:Copy> ExtendedTupleOps<A,B> for (&'self [A], &'self [B]) {
    #[inline(always)]
    fn zip(&self) -> ~[(A, B)] {
        match *self {
            (ref a, ref b) => {
                vec::zip_slice(*a, *b)
            }
        }
    }

    #[inline(always)]
    fn map<C>(&self, f: &fn(a: &A, b: &B) -> C) -> ~[C] {
        match *self {
            (ref a, ref b) => {
                vec::map2(*a, *b, f)
            }
        }
    }
}

impl<A:Copy,B:Copy> ExtendedTupleOps<A,B> for (~[A], ~[B]) {

    #[inline(always)]
    fn zip(&self) -> ~[(A, B)] {
        match *self {
            (ref a, ref b) => {
                vec::zip_slice(*a, *b)
            }
        }
    }

    #[inline(always)]
    fn map<C>(&self, f: &fn(a: &A, b: &B) -> C) -> ~[C] {
        match *self {
            (ref a, ref b) => {
                vec::map2(*a, *b, f)
            }
        }
    }
}

#[cfg(notest)]
impl<A:Eq> Eq for (A,) {
    #[inline(always)]
    fn eq(&self, other: &(A,)) -> bool {
        match (*self) {
            (ref self_a,) => match other {
                &(ref other_a,) => {
                    (*self_a).eq(other_a)
                }
            }
        }
    }
    #[inline(always)]
    fn ne(&self, other: &(A,)) -> bool { !(*self).eq(other) }
}

#[cfg(notest)]
impl<A:Ord> Ord for (A,) {
    #[inline(always)]
    fn lt(&self, other: &(A,)) -> bool {
        match (*self) {
            (ref self_a,) => {
                match (*other) {
                    (ref other_a,) => {
                        if (*self_a).lt(other_a) { return true; }
                        return false;
                    }
                }
            }
        }
    }
    #[inline(always)]
    fn le(&self, other: &(A,)) -> bool { !other.lt(&(*self)) }
    #[inline(always)]
    fn ge(&self, other: &(A,)) -> bool { !self.lt(other) }
    #[inline(always)]
    fn gt(&self, other: &(A,)) -> bool { other.lt(&(*self))  }
}

#[cfg(notest)]
impl<A:Eq,B:Eq> Eq for (A, B) {
    #[inline(always)]
    fn eq(&self, other: &(A, B)) -> bool {
        match (*self) {
            (ref self_a, ref self_b) => match other {
                &(ref other_a, ref other_b) => {
                    (*self_a).eq(other_a) && (*self_b).eq(other_b)
                }
            }
        }
    }
    #[inline(always)]
    fn ne(&self, other: &(A, B)) -> bool { !(*self).eq(other) }
}

#[cfg(notest)]
impl<A:Ord,B:Ord> Ord for (A, B) {
    #[inline(always)]
    fn lt(&self, other: &(A, B)) -> bool {
        match (*self) {
            (ref self_a, ref self_b) => {
                match (*other) {
                    (ref other_a, ref other_b) => {
                        if (*self_a).lt(other_a) { return true; }
                        if (*other_a).lt(self_a) { return false; }
                        if (*self_b).lt(other_b) { return true; }
                        return false;
                    }
                }
            }
        }
    }
    #[inline(always)]
    fn le(&self, other: &(A, B)) -> bool { !(*other).lt(&(*self)) }
    #[inline(always)]
    fn ge(&self, other: &(A, B)) -> bool { !(*self).lt(other) }
    #[inline(always)]
    fn gt(&self, other: &(A, B)) -> bool { (*other).lt(&(*self))  }
}

#[cfg(notest)]
impl<A:Eq,B:Eq,C:Eq> Eq for (A, B, C) {
    #[inline(always)]
    fn eq(&self, other: &(A, B, C)) -> bool {
        match (*self) {
            (ref self_a, ref self_b, ref self_c) => match other {
                &(ref other_a, ref other_b, ref other_c) => {
                    (*self_a).eq(other_a) && (*self_b).eq(other_b)
                        && (*self_c).eq(other_c)
                }
            }
        }
    }
    #[inline(always)]
    fn ne(&self, other: &(A, B, C)) -> bool { !(*self).eq(other) }
}

#[cfg(notest)]
impl<A:Ord,B:Ord,C:Ord> Ord for (A, B, C) {
    #[inline(always)]
    fn lt(&self, other: &(A, B, C)) -> bool {
        match (*self) {
            (ref self_a, ref self_b, ref self_c) => {
                match (*other) {
                    (ref other_a, ref other_b, ref other_c) => {
                        if (*self_a).lt(other_a) { return true; }
                        if (*other_a).lt(self_a) { return false; }
                        if (*self_b).lt(other_b) { return true; }
                        if (*other_b).lt(self_b) { return false; }
                        if (*self_c).lt(other_c) { return true; }
                        return false;
                    }
                }
            }
        }
    }
    #[inline(always)]
    fn le(&self, other: &(A, B, C)) -> bool { !(*other).lt(&(*self)) }
    #[inline(always)]
    fn ge(&self, other: &(A, B, C)) -> bool { !(*self).lt(other) }
    #[inline(always)]
    fn gt(&self, other: &(A, B, C)) -> bool { (*other).lt(&(*self))  }
}

#[test]
fn test_tuple_ref() {
    let x = (~"foo", ~"bar");
    assert!(x.first_ref() == &~"foo");
    assert!(x.second_ref() == &~"bar");
}

#[test]
#[allow(non_implicitly_copyable_typarams)]
fn test_tuple() {
    assert!((948, 4039.48).first() == 948);
    assert!((34.5, ~"foo").second() == ~"foo");
    assert!(('a', 2).swap() == (2, 'a'));
}

<commit_msg>Implement Clone for tuples<commit_after>// Copyright 2012 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.

//! Operations on tuples

use clone::Clone;
use kinds::Copy;
use vec;

#[cfg(notest)] use cmp::{Eq, Ord};

pub trait CopyableTuple<T, U> {
    fn first(&self) -> T;
    fn second(&self) -> U;
    fn swap(&self) -> (U, T);
}

impl<T:Copy,U:Copy> CopyableTuple<T, U> for (T, U) {

    /// Return the first element of self
    #[inline(always)]
    fn first(&self) -> T {
        let (t, _) = *self;
        return t;
    }

    /// Return the second element of self
    #[inline(always)]
    fn second(&self) -> U {
        let (_, u) = *self;
        return u;
    }

    /// Return the results of swapping the two elements of self
    #[inline(always)]
    fn swap(&self) -> (U, T) {
        let (t, u) = *self;
        return (u, t);
    }

}

impl<T:Clone,U:Clone> Clone for (T, U) {
    fn clone(&self) -> (T, U) {
        let (a, b) = match *self {
            (ref a, ref b) => (a, b)
        };
        (a.clone(), b.clone())
    }
}

pub trait ImmutableTuple<T, U> {
    fn first_ref(&self) -> &'self T;
    fn second_ref(&self) -> &'self U;
}

impl<T, U> ImmutableTuple<T, U> for (T, U) {
    #[inline(always)]
    fn first_ref(&self) -> &'self T {
        match *self {
            (ref t, _) => t,
        }
    }
    #[inline(always)]
    fn second_ref(&self) -> &'self U {
        match *self {
            (_, ref u) => u,
        }
    }
}

pub trait ExtendedTupleOps<A,B> {
    fn zip(&self) -> ~[(A, B)];
    fn map<C>(&self, f: &fn(a: &A, b: &B) -> C) -> ~[C];
}

impl<'self,A:Copy,B:Copy> ExtendedTupleOps<A,B> for (&'self [A], &'self [B]) {
    #[inline(always)]
    fn zip(&self) -> ~[(A, B)] {
        match *self {
            (ref a, ref b) => {
                vec::zip_slice(*a, *b)
            }
        }
    }

    #[inline(always)]
    fn map<C>(&self, f: &fn(a: &A, b: &B) -> C) -> ~[C] {
        match *self {
            (ref a, ref b) => {
                vec::map2(*a, *b, f)
            }
        }
    }
}

impl<A:Copy,B:Copy> ExtendedTupleOps<A,B> for (~[A], ~[B]) {

    #[inline(always)]
    fn zip(&self) -> ~[(A, B)] {
        match *self {
            (ref a, ref b) => {
                vec::zip_slice(*a, *b)
            }
        }
    }

    #[inline(always)]
    fn map<C>(&self, f: &fn(a: &A, b: &B) -> C) -> ~[C] {
        match *self {
            (ref a, ref b) => {
                vec::map2(*a, *b, f)
            }
        }
    }
}

#[cfg(notest)]
impl<A:Eq> Eq for (A,) {
    #[inline(always)]
    fn eq(&self, other: &(A,)) -> bool {
        match (*self) {
            (ref self_a,) => match other {
                &(ref other_a,) => {
                    (*self_a).eq(other_a)
                }
            }
        }
    }
    #[inline(always)]
    fn ne(&self, other: &(A,)) -> bool { !(*self).eq(other) }
}

#[cfg(notest)]
impl<A:Ord> Ord for (A,) {
    #[inline(always)]
    fn lt(&self, other: &(A,)) -> bool {
        match (*self) {
            (ref self_a,) => {
                match (*other) {
                    (ref other_a,) => {
                        if (*self_a).lt(other_a) { return true; }
                        return false;
                    }
                }
            }
        }
    }
    #[inline(always)]
    fn le(&self, other: &(A,)) -> bool { !other.lt(&(*self)) }
    #[inline(always)]
    fn ge(&self, other: &(A,)) -> bool { !self.lt(other) }
    #[inline(always)]
    fn gt(&self, other: &(A,)) -> bool { other.lt(&(*self))  }
}

#[cfg(notest)]
impl<A:Eq,B:Eq> Eq for (A, B) {
    #[inline(always)]
    fn eq(&self, other: &(A, B)) -> bool {
        match (*self) {
            (ref self_a, ref self_b) => match other {
                &(ref other_a, ref other_b) => {
                    (*self_a).eq(other_a) && (*self_b).eq(other_b)
                }
            }
        }
    }
    #[inline(always)]
    fn ne(&self, other: &(A, B)) -> bool { !(*self).eq(other) }
}

#[cfg(notest)]
impl<A:Ord,B:Ord> Ord for (A, B) {
    #[inline(always)]
    fn lt(&self, other: &(A, B)) -> bool {
        match (*self) {
            (ref self_a, ref self_b) => {
                match (*other) {
                    (ref other_a, ref other_b) => {
                        if (*self_a).lt(other_a) { return true; }
                        if (*other_a).lt(self_a) { return false; }
                        if (*self_b).lt(other_b) { return true; }
                        return false;
                    }
                }
            }
        }
    }
    #[inline(always)]
    fn le(&self, other: &(A, B)) -> bool { !(*other).lt(&(*self)) }
    #[inline(always)]
    fn ge(&self, other: &(A, B)) -> bool { !(*self).lt(other) }
    #[inline(always)]
    fn gt(&self, other: &(A, B)) -> bool { (*other).lt(&(*self))  }
}

#[cfg(notest)]
impl<A:Eq,B:Eq,C:Eq> Eq for (A, B, C) {
    #[inline(always)]
    fn eq(&self, other: &(A, B, C)) -> bool {
        match (*self) {
            (ref self_a, ref self_b, ref self_c) => match other {
                &(ref other_a, ref other_b, ref other_c) => {
                    (*self_a).eq(other_a) && (*self_b).eq(other_b)
                        && (*self_c).eq(other_c)
                }
            }
        }
    }
    #[inline(always)]
    fn ne(&self, other: &(A, B, C)) -> bool { !(*self).eq(other) }
}

#[cfg(notest)]
impl<A:Ord,B:Ord,C:Ord> Ord for (A, B, C) {
    #[inline(always)]
    fn lt(&self, other: &(A, B, C)) -> bool {
        match (*self) {
            (ref self_a, ref self_b, ref self_c) => {
                match (*other) {
                    (ref other_a, ref other_b, ref other_c) => {
                        if (*self_a).lt(other_a) { return true; }
                        if (*other_a).lt(self_a) { return false; }
                        if (*self_b).lt(other_b) { return true; }
                        if (*other_b).lt(self_b) { return false; }
                        if (*self_c).lt(other_c) { return true; }
                        return false;
                    }
                }
            }
        }
    }
    #[inline(always)]
    fn le(&self, other: &(A, B, C)) -> bool { !(*other).lt(&(*self)) }
    #[inline(always)]
    fn ge(&self, other: &(A, B, C)) -> bool { !(*self).lt(other) }
    #[inline(always)]
    fn gt(&self, other: &(A, B, C)) -> bool { (*other).lt(&(*self))  }
}

#[test]
fn test_tuple_ref() {
    let x = (~"foo", ~"bar");
    assert!(x.first_ref() == &~"foo");
    assert!(x.second_ref() == &~"bar");
}

#[test]
#[allow(non_implicitly_copyable_typarams)]
fn test_tuple() {
    assert!((948, 4039.48).first() == 948);
    assert!((34.5, ~"foo").second() == ~"foo");
    assert!(('a', 2).swap() == (2, 'a'));
}

#[test]
fn test_clone() {
    let a = (1, ~"2");
    let b = a.clone();
    assert!(a.first() == b.first());
    assert!(a.second() == b.second());
}
<|endoftext|>


<commit_before>//! An implementation of disjoint set forests for union find.

/// Data structure for efficient union find.
pub struct DisjointSetForest {
    /// Number of forest elements.
    count: usize,
    /// parent[i] is the index of the parent
    /// of the element with index i. If parent[i] == i
    /// then i is a root.
    parent: Vec<usize>,
    /// tree_size[i] is the size of the tree rooted at i.
    tree_size: Vec<usize>,
}

impl DisjointSetForest {

    /// Constructs forest of singletons with count elements.
    pub fn new(count: usize) -> DisjointSetForest {
        let mut parent = vec![0 as usize; count];
        for i in 0..count {
            parent[i] = i;
        }
        let tree_size = vec![1 as usize; count];
        DisjointSetForest {
            count: count,
            parent: parent,
            tree_size: tree_size}
    }

    /// Returns the number of trees in the forest.
    pub fn num_trees(&self) -> usize {
        self.parent
            .iter()
            .enumerate()
            .fold(0, |acc, (i, p)| acc + if i == *p { 1 } else { 0 })
    }

    /// Returns index of the root of the tree containing i.
    /// Needs mutable reference to self for path compression.
    pub fn root(&mut self, i: usize) -> usize {
        let mut j = i;
        loop {
            unsafe {
                let p = *self.parent.get_unchecked(j);
                *self.parent.get_unchecked_mut(j) = *self.parent.get_unchecked(p);
                if j == p {
                    break;
                }
                j = p;
            }
        }
        j
    }

    /// Returns true if i and j are in the same tree.
    /// Need mutable reference to self for path compression.
    pub fn find(&mut self, i: usize, j: usize) -> bool {
        self.root(i) == self.root(j)
    }

    /// Unions the trees containing i and j.
    pub fn union(&mut self, i: usize, j: usize) {
        let p = self.root(i);
        let q = self.root(j);
        if p == q {
            return;
        }
        unsafe {
            let p_size = *self.tree_size.get_unchecked(p);
            let q_size = *self.tree_size.get_unchecked(q);
            if p_size < q_size {
                *self.parent.get_unchecked_mut(p) = q;
                *self.tree_size.get_unchecked_mut(q) = p_size + q_size;
            }
            else {
                *self.parent.get_unchecked_mut(q) = p;
                *self.tree_size.get_unchecked_mut(p) = p_size + q_size;
            }
        }
    }

    /// Returns the elements of each tree.
    pub fn trees(&mut self) -> Vec<Vec<usize>> {
        use std::collections::HashMap;

        // Maps a tree root to the index of the set
        // containing its children
        let mut root_sets: HashMap<usize, usize> = HashMap::new();

        let mut sets: Vec<Vec<usize>> = vec![];
        for i in 0..self.count {
            let root = self.root(i);
            match root_sets.get(&root).cloned() {
                Some(set_idx) => {
                    sets[set_idx].push(i);
                },
                None => {
                    let idx = sets.len();
                    let set = vec![i];
                    sets.push(set);
                    root_sets.insert(root, idx);
                }
            }
        }
        sets
    }
}

#[cfg(test)]
mod test {

    use super::DisjointSetForest;
    use test;
    use rand::{SeedableRng, StdRng};
    use rand::distributions::{IndependentSample, Range};

    #[test]
    fn test_trees() {
        //    3         4
        //    |        /  \
        //    1       5    7
        //   /  \     |
        //  0    2    6
        let mut forest = DisjointSetForest {
            count: 8,
            // element:     0, 1, 2, 3, 4, 5, 6, 7
            parent:    vec![1, 3, 1, 3, 4, 4, 5, 4],
            tree_size: vec![1, 3, 1, 4, 4, 2, 1, 1]
        };

        assert_eq!(forest.trees(),
            vec![vec![0, 1, 2, 3], vec![4, 5, 6, 7]]);
    }

    #[test]
    fn test_union_find_sequence() {

        let mut forest = DisjointSetForest::new(6);
        // 0  1  2  3  4  5

        //                             0, 1, 2, 3, 4, 5
        assert_eq!(forest.parent, vec![0, 1, 2, 3, 4, 5]);
        assert_eq!(forest.num_trees(), 6);

        forest.union(0, 4);
        // 0  1  2  3  5
        // |
        // 4

        //                             0, 1, 2, 3, 4, 5
        assert_eq!(forest.parent, vec![0, 1, 2, 3, 0, 5]);
        assert_eq!(forest.num_trees(), 5);

        forest.union(1, 3);
        // 0  1  2  5
        // |  |
        // 4  3

        //                             0, 1, 2, 3, 4, 5
        assert_eq!(forest.parent, vec![0, 1, 2, 1, 0, 5]);
        assert_eq!(forest.num_trees(), 4);

        forest.union(3, 2);
        // 0    1     5
        // |   / \
        // 4  3   2

        //                             0, 1, 2, 3, 4, 5
        assert_eq!(forest.parent, vec![0, 1, 1, 1, 0, 5]);
        assert_eq!(forest.num_trees(), 3);

        forest.union(2, 4);
        //    1     5
        //  / | \
        // 0  3  2
        // |
        // 4

        //                             0, 1, 2, 3, 4, 5
        assert_eq!(forest.parent, vec![1, 1, 1, 1, 0, 5]);
        assert_eq!(forest.num_trees(), 2);
    }

    #[bench]
    fn bench_disjoint_set_forest(b: &mut test::Bencher) {
        let num_nodes = 500;
        let num_edges = 20 * num_nodes;

        let seed_array: &[_] = &[1usize];
        let mut rng: StdRng = SeedableRng::from_seed(seed_array);
        let uniform = Range::new(0, num_nodes + 1);

        let mut forest = DisjointSetForest::new(num_nodes);
        b.iter(|| {
            let mut count = 0;
            while count < num_edges {
                let u = uniform.ind_sample(&mut rng);
                let v = uniform.ind_sample(&mut rng);
                forest.union(u, v);
                count += 1;
            }
            test::black_box(forest.num_trees());
        });
    }
}
<commit_msg>Fix index<commit_after>//! An implementation of disjoint set forests for union find.

/// Data structure for efficient union find.
pub struct DisjointSetForest {
    /// Number of forest elements.
    count: usize,
    /// parent[i] is the index of the parent
    /// of the element with index i. If parent[i] == i
    /// then i is a root.
    parent: Vec<usize>,
    /// tree_size[i] is the size of the tree rooted at i.
    tree_size: Vec<usize>,
}

impl DisjointSetForest {

    /// Constructs forest of singletons with count elements.
    pub fn new(count: usize) -> DisjointSetForest {
        let mut parent = vec![0 as usize; count];
        for i in 0..count {
            parent[i] = i;
        }
        let tree_size = vec![1 as usize; count];
        DisjointSetForest {
            count: count,
            parent: parent,
            tree_size: tree_size}
    }

    /// Returns the number of trees in the forest.
    pub fn num_trees(&self) -> usize {
        self.parent
            .iter()
            .enumerate()
            .fold(0, |acc, (i, p)| acc + if i == *p { 1 } else { 0 })
    }

    /// Returns index of the root of the tree containing i.
    /// Needs mutable reference to self for path compression.
    pub fn root(&mut self, i: usize) -> usize {
        let mut j = i;
        loop {
            unsafe {
                let p = *self.parent.get_unchecked(j);
                *self.parent.get_unchecked_mut(j) = *self.parent.get_unchecked(p);
                if j == p {
                    break;
                }
                j = p;
            }
        }
        j
    }

    /// Returns true if i and j are in the same tree.
    /// Need mutable reference to self for path compression.
    pub fn find(&mut self, i: usize, j: usize) -> bool {
        self.root(i) == self.root(j)
    }

    /// Unions the trees containing i and j.
    pub fn union(&mut self, i: usize, j: usize) {
        let p = self.root(i);
        let q = self.root(j);
        if p == q {
            return;
        }
        unsafe {
            let p_size = *self.tree_size.get_unchecked(p);
            let q_size = *self.tree_size.get_unchecked(q);
            if p_size < q_size {
                *self.parent.get_unchecked_mut(p) = q;
                *self.tree_size.get_unchecked_mut(q) = p_size + q_size;
            }
            else {
                *self.parent.get_unchecked_mut(q) = p;
                *self.tree_size.get_unchecked_mut(p) = p_size + q_size;
            }
        }
    }

    /// Returns the elements of each tree.
    pub fn trees(&mut self) -> Vec<Vec<usize>> {
        use std::collections::HashMap;

        // Maps a tree root to the index of the set
        // containing its children
        let mut root_sets: HashMap<usize, usize> = HashMap::new();

        let mut sets: Vec<Vec<usize>> = vec![];
        for i in 0..self.count {
            let root = self.root(i);
            match root_sets.get(&root).cloned() {
                Some(set_idx) => {
                    sets[set_idx].push(i);
                },
                None => {
                    let idx = sets.len();
                    let set = vec![i];
                    sets.push(set);
                    root_sets.insert(root, idx);
                }
            }
        }
        sets
    }
}

#[cfg(test)]
mod test {

    use super::DisjointSetForest;
    use test;
    use rand::{SeedableRng, StdRng};
    use rand::distributions::{IndependentSample, Range};

    #[test]
    fn test_trees() {
        //    3         4
        //    |        /  \
        //    1       5    7
        //   /  \     |
        //  0    2    6
        let mut forest = DisjointSetForest {
            count: 8,
            // element:     0, 1, 2, 3, 4, 5, 6, 7
            parent:    vec![1, 3, 1, 3, 4, 4, 5, 4],
            tree_size: vec![1, 3, 1, 4, 4, 2, 1, 1]
        };

        assert_eq!(forest.trees(),
            vec![vec![0, 1, 2, 3], vec![4, 5, 6, 7]]);
    }

    #[test]
    fn test_union_find_sequence() {

        let mut forest = DisjointSetForest::new(6);
        // 0  1  2  3  4  5

        //                             0, 1, 2, 3, 4, 5
        assert_eq!(forest.parent, vec![0, 1, 2, 3, 4, 5]);
        assert_eq!(forest.num_trees(), 6);

        forest.union(0, 4);
        // 0  1  2  3  5
        // |
        // 4

        //                             0, 1, 2, 3, 4, 5
        assert_eq!(forest.parent, vec![0, 1, 2, 3, 0, 5]);
        assert_eq!(forest.num_trees(), 5);

        forest.union(1, 3);
        // 0  1  2  5
        // |  |
        // 4  3

        //                             0, 1, 2, 3, 4, 5
        assert_eq!(forest.parent, vec![0, 1, 2, 1, 0, 5]);
        assert_eq!(forest.num_trees(), 4);

        forest.union(3, 2);
        // 0    1     5
        // |   / \
        // 4  3   2

        //                             0, 1, 2, 3, 4, 5
        assert_eq!(forest.parent, vec![0, 1, 1, 1, 0, 5]);
        assert_eq!(forest.num_trees(), 3);

        forest.union(2, 4);
        //    1     5
        //  / | \
        // 0  3  2
        // |
        // 4

        //                             0, 1, 2, 3, 4, 5
        assert_eq!(forest.parent, vec![1, 1, 1, 1, 0, 5]);
        assert_eq!(forest.num_trees(), 2);
    }

    #[bench]
    fn bench_disjoint_set_forest(b: &mut test::Bencher) {
        let num_nodes = 500;
        let num_edges = 20 * num_nodes;

        let seed_array: &[_] = &[1usize];
        let mut rng: StdRng = SeedableRng::from_seed(seed_array);
        let uniform = Range::new(0, num_nodes);

        let mut forest = DisjointSetForest::new(num_nodes);
        b.iter(|| {
            let mut count = 0;
            while count < num_edges {
                let u = uniform.ind_sample(&mut rng);
                let v = uniform.ind_sample(&mut rng);
                forest.union(u, v);
                count += 1;
            }
            test::black_box(forest.num_trees());
        });
    }
}
<|endoftext|>


<commit_before>#[derive(Debug, Deserialize)]
pub struct User {
    pub login: String,
    pub id: u64,
    pub avatar_url: String,
    pub gravatar_id: String,
    pub url: String,
    pub html_url: String,
    pub followers_url: String,
    pub following_url: String,
    pub gists_url: String,
    pub starred_url: String,
    pub subscriptions_url: String,
    pub organizations_url: String,
    pub repos_url: String,
    pub events_url: String,
    pub received_events_url: String,
    // type (keyword)
    pub site_admin: bool,
}
<commit_msg>mod doc<commit_after>//! Users interface

#[derive(Debug, Deserialize)]
pub struct User {
    pub login: String,
    pub id: u64,
    pub avatar_url: String,
    pub gravatar_id: String,
    pub url: String,
    pub html_url: String,
    pub followers_url: String,
    pub following_url: String,
    pub gists_url: String,
    pub starred_url: String,
    pub subscriptions_url: String,
    pub organizations_url: String,
    pub repos_url: String,
    pub events_url: String,
    pub received_events_url: String,
    // type (keyword)
    pub site_admin: bool,
}
<|endoftext|>