<commit_before>use std::io::File;
use std::mem;
use std::num::Int;
use std::os;

// https://stackoverflow.com/questions/24633784/is-there-a-gzip-library-available-for-rust

fn pointer_size() -> usize {
    let tmp = 0u8;
    let boxed = Box::new(tmp);
    mem::size_of_val(&boxed)
}

fn main() {
    let args = os::args();
    if args.len() != 2 {
        println!("usage: read_blend_file /path/to/file.blend");
    } else {
        let slice: &str = args[1].as_slice();
        println!("open \"{}\" ...", slice);
        {
            // read 12 bytes from the Blender file
            let path = Path::new(slice);
            let display = path.display();
            let mut file = match File::open(&path) {
                Err(why) => panic!("couldn't open {}: {}", display, why.desc),
                Ok(file) => file,
            };
            let io_result = file.read_exact(12);
            let buf = io_result.unwrap();
            // pack those 12 bytes into a string ...
            let mut header = String::new();
            for e in buf.iter() {
                header.push(*e as char);
            }
            // ... to be able to compare them
            let slice = header.as_slice();
            let blender: &str = slice.slice(0, 7); // first 7 chars
            if blender == "BLENDER" {
                println!("INFO: a Blender file.");
                let ptr_size = pointer_size();
                println!("size of pointer in bytes: {}", ptr_size);
                println!("Header (12 chars): {}", header);
                let mut ptr_size_differs = false;
                if buf[7] as char == '_' {
                    // 32-bit pointers expected
                    if ptr_size != 4 {
                        ptr_size_differs = true;
                    }
                    println!("32-bit pointers in file, pointer size differs? {}", ptr_size_differs);
                } else {
                    // 64-bit pointers expected
                    if ptr_size != 8 {
                        ptr_size_differs = true;
                    }
                    println!("64-bit pointers in file, pointer size differs? {}", ptr_size_differs);
                }
                // little endian or big endian?
                let mut l_endian;
                let endian_test = 1u16; // value one stored in two bytes
                if endian_test.to_le() != endian_test {
                    l_endian = false;
                } else {
                    // if we are on a little endian machine to_le() is a no-op
                    l_endian = true;
                }
                println!("l_endian = {}", l_endian);
                let mut switch_endian;
                if buf[8] as char == 'v' {
                    // file stores little endian
                    if !l_endian {
                        switch_endian = true;
                    } else {
                        switch_endian = false;
                    }
                } else {
                    // file stores big endian
                    if l_endian {
                        switch_endian = true;
                    } else {
                        switch_endian = false;
                    }
                }
                println!("switch_endian = {}", switch_endian);
                // get the version number
                let num: &str = slice.slice(9, 12); // last 3 chars
                println!("num = {}", num);
                // assumes 64-bit pointers (in file as well as on platform)
                loop {
                    // read_file_dna
                    let io_result = file.read_exact(24); // 4 * int + 64-bit pointer
                    let bhead8 = io_result.unwrap();
                    // pack those 24 bytes into a string ...
                    let mut bhead = String::new();
                    for e in bhead8.iter() {
                        bhead.push(*e as char);
                    }
                    let slice = bhead.as_slice();
                    let code: &str = slice.slice(0, 4); // first 4 chars
                    println!("code = {}", code);
                    let mut len: u32 = 0;
                    len += (bhead8[4] as u32) <<  0;
                    len += (bhead8[5] as u32) <<  8;
                    len += (bhead8[6] as u32) << 16;
                    len += (bhead8[7] as u32) << 24;
                    println!("len = {}", len);
                    if code == "ENDB" && len == 0 {
                        break;
                    } else if code == "DNA1" {
                        // DNA_sdna_from_data
                        let mut counter = 0u32;
                        // SDNA
                        let io_result = file.read_exact(4);
                        let char4 = io_result.unwrap();
                        counter += 4;
                        let mut str4 = String::new();
                        for e in char4.iter() {
                            str4.push(*e as char);
                        }
                        let slice = str4.as_slice();
                        let code: &str = slice.slice(0, 4);
                        println!("  code = {}", code);
                        if code == "SDNA" {
                            // NAME
                            let io_result = file.read_exact(4);
                            let char4 = io_result.unwrap();
                            counter += 4;
                            let mut str4 = String::new();
                            for e in char4.iter() {
                                str4.push(*e as char);
                            }
                            let slice = str4.as_slice();
                            let code: &str = slice.slice(0, 4);
                            println!("  code = {}", code);
                            if code == "NAME" {
                                // nr_names
                                let io_result = file.read_le_u32();
                                let nr_names: u32 = io_result.unwrap();
                                counter += 4;
                                println!("  nr_names = {}", nr_names);
                                let mut nr = 0u32;
                                loop {
                                    let mut name = String::new();
                                    loop {
                                        // expect strings with '\0' as terminator
                                        let io_result = file.read_byte();
                                        let byte: u8 = io_result.unwrap();
                                        counter += 1;
                                        if byte != 0 {
                                            name.push(byte as char);
                                        } else {
                                            println!("    name = '{}'", name);
                                            nr += 1;
                                            break;
                                        }
                                    } // name loop
                                    if nr >= nr_names {
                                        break;
                                    }
                                } // nr_names loop
                                // assume fill bytes with '\0'
                                let mut last_byte;
                                loop {
                                    let io_result = file.read_byte();
                                    let byte: u8 = io_result.unwrap();
                                    counter += 1;
                                    if byte != 0 {
                                        last_byte = byte;
                                        break;
                                    }
                                } // fill bytes
                                // TYPE
                                let io_result = file.read_exact(3);
                                let char3 = io_result.unwrap();
                                counter += 3;
                                let mut str4 = String::new();
                                str4.push(last_byte as char);
                                for e in char3.iter() {
                                    str4.push(*e as char);
                                }
                                let slice = str4.as_slice();
                                let code: &str = slice.slice(0, 4);
                                println!("  code = {}", code);
                                if code == "TYPE" {
                                    // nr_types
                                    let io_result = file.read_le_u32();
                                    let nr_types: u32 = io_result.unwrap();
                                    counter += 4;
                                    println!("  nr_types = {}", nr_types);
                                    let mut nr = 0u32;
                                    loop {
                                        let mut name = String::new();
                                        loop {
                                            // expect strings with
                                            // '\0' as terminator
                                            let io_result = file.read_byte();
                                            let byte: u8 = io_result.unwrap();
                                            counter += 1;
                                            if byte != 0 {
                                                name.push(byte as char);
                                            } else {
                                                println!("    type = '{}'",
                                                         name);
                                                nr += 1;
                                                break;
                                            }
                                        } // type loop
                                        if nr >= nr_types {
                                            break;
                                        }
                                    } // nr_types loop
                                    // assume fill bytes with '\0'
                                    let mut last_byte;
                                    loop {
                                        let io_result = file.read_byte();
                                        let byte: u8 = io_result.unwrap();
                                        counter += 1;
                                        if byte != 0 {
                                            last_byte = byte;
                                            break;
                                        }
                                    } // fill bytes
                                    // TLEN
                                    let io_result = file.read_exact(3);
                                    let char3 = io_result.unwrap();
                                    counter += 3;
                                    let mut str4 = String::new();
                                    str4.push(last_byte as char);
                                    for e in char3.iter() {
                                        str4.push(*e as char);
                                    }
                                    let slice = str4.as_slice();
                                    let code: &str = slice.slice(0, 4);
                                    println!("  code = {}", code);
                                    if code == "TLEN" {
                                        // typelens
                                        let io_result = file.read_le_u16();
                                        let typelens: u16 = io_result.unwrap();
                                        counter += 2;
                                        println!("    typelens = {}", typelens);
                                        // skip nr_types times u16 values
                                        let _dummy = file.read_exact((2u32 *
                                                                     nr_types) as
                                                                     usize);
                                        counter += 2u32 * nr_types as u32;
                                        // check next byte
                                        let io_result = file.read_byte();
                                        last_byte = io_result.unwrap();
                                        counter += 1;
                                        if last_byte == 0 {
                                            let io_result = file.read_byte();
                                            last_byte = io_result.unwrap();
                                            counter += 1;
                                        }
                                        // STRC
                                        let io_result = file.read_exact(3);
                                        let char3 = io_result.unwrap();
                                        counter += 3;
                                        let mut str4 = String::new();
                                        str4.push(last_byte as char);
                                        for e in char3.iter() {
                                            str4.push(*e as char);
                                        }
                                        let slice = str4.as_slice();
                                        let code: &str = slice.slice(0, 4);
                                        println!("  code = {}", code);
                                        if code == "STRC" {
                                            // nr_structs
                                            let io_result = file.read_le_u32();
                                            let nr_structs: u32 = io_result.unwrap();
                                            counter += 4;
                                            println!("    nr_structs = {}", nr_structs);
                                            nr = 0u32;
                                            loop {
                                                // sp0
                                                let io_result = file.read_le_u16();
                                                let _sp0: u16 = io_result.unwrap();
                                                counter += 2;
                                                // sp1
                                                let io_result = file.read_le_u16();
                                                let sp1: u16 = io_result.unwrap();
                                                counter += 2;
                                                for _n in range(0u16, 2 * sp1) {
                                                    let io_result = file.read_le_u16();
                                                    let _u: u16 = io_result.unwrap();
                                                    counter += 2;
                                                }
                                                nr += 1;
                                                if nr >= nr_structs {
                                                    break;
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        // read remaining stuff
                        println!("skip {} bytes", len - counter);
                        let _dummy = file.read_exact((len - counter) as usize);
                    } else {
                        let tc: &str = slice.slice(0, 2); // first 2 chars
                        if tc == "CA" {
                            let mut counter = 0u32;
                            // struct ID (see DNA_ID.h)
                            let _next = file.read_le_u64();
                            counter += 8;
                            let _prev = file.read_le_u64();
                            counter += 8;
                            let _newid = file.read_le_u64();
                            counter += 8;
                            let _lib = file.read_le_u64();
                            counter += 8;
                            let io_result = file.read_exact(66);
                            let bname = io_result.unwrap();
                            // pack those 66 bytes into a string ...
                            let mut name = String::new();
                            for e in bname.iter() {
                                if *e == 0u8 {
                                    // ... but stop as soon as you see '\0'
                                    break;
                                } else {
                                    name.push(*e as char);
                                }
                            }
                            counter += 66;
                            let _flag = file.read_le_u16();
                            counter += 2;
                            let _us = file.read_le_u32();
                            counter += 4;
                            let _icon_id = file.read_le_u32();
                            counter += 4;
                            let _pad2 = file.read_le_u32();
                            counter += 4;
                            let _properties = file.read_le_u64();
                            counter += 8;
                            // struct Camera (see DNA_camera_types.h)
                            let _adt = file.read_le_u64();
                            counter += 8;
                            let io_result = file.read_u8();
                            let cam_type: u8 = io_result.unwrap();
                            counter += 1;
                            let _dtx = file.read_u8();
                            counter += 1;
                            let _flag = file.read_le_u16();
                            counter += 2;
                            let _passepartalpha = file.read_le_f32();
                            counter += 4;
                            let _clipsta = file.read_le_f32();
                            counter += 4;
                            let _clipend = file.read_le_f32();
                            counter += 4;
                            let io_result = file.read_le_f32();
                            let lens: f32 = io_result.unwrap();
                            counter += 4;
                            let _dummy = file.read_exact((len - counter) as usize);
                            if cam_type == 0u8 {
                                println!("Camera({}, {}, {})", name, "CAM_PERSP", lens)
                            } else {
                                println!("Camera({}, {}, {})", name, cam_type, lens)
                            }
                        } else {
                            let _dummy = file.read_exact(len as usize);
                        }
                    }
                }
            } else {
                println!("ERROR: not a Blender file.");
            }
        } // file gets closed here
    }
}
<commit_msg>Avoid using as_slice().<commit_after>use std::io::File;
use std::mem;
use std::num::Int;
use std::os;

// https://stackoverflow.com/questions/24633784/is-there-a-gzip-library-available-for-rust

fn pointer_size() -> usize {
    let tmp = 0u8;
    let boxed = Box::new(tmp);
    mem::size_of_val(&boxed)
}

fn main() {
    let args = os::args();
    if args.len() != 2 {
        println!("usage: read_blend_file /path/to/file.blend");
    } else {
        let slice: &str = args[1].as_slice();
        println!("open \"{}\" ...", slice);
        {
            // read 12 bytes from the Blender file
            let path = Path::new(slice);
            let display = path.display();
            let mut file = match File::open(&path) {
                Err(why) => panic!("couldn't open {}: {}", display, why.desc),
                Ok(file) => file,
            };
            let io_result = file.read_exact(12);
            let buf = io_result.unwrap();
            // pack those 12 bytes into a string ...
            let mut header = String::new();
            for e in buf.iter() {
                header.push(*e as char);
            }
            // ... to be able to compare them
            let blender: &str = header.slice(0, 7); // first 7 chars
            if blender == "BLENDER" {
                println!("INFO: a Blender file.");
                let ptr_size = pointer_size();
                println!("size of pointer in bytes: {}", ptr_size);
                println!("Header (12 chars): {}", header);
                let mut ptr_size_differs = false;
                if buf[7] as char == '_' {
                    // 32-bit pointers expected
                    if ptr_size != 4 {
                        ptr_size_differs = true;
                    }
                    println!("32-bit pointers in file, pointer size differs? {}", ptr_size_differs);
                } else {
                    // 64-bit pointers expected
                    if ptr_size != 8 {
                        ptr_size_differs = true;
                    }
                    println!("64-bit pointers in file, pointer size differs? {}", ptr_size_differs);
                }
                // little endian or big endian?
                let mut l_endian;
                let endian_test = 1u16; // value one stored in two bytes
                if endian_test.to_le() != endian_test {
                    l_endian = false;
                } else {
                    // if we are on a little endian machine to_le() is a no-op
                    l_endian = true;
                }
                println!("l_endian = {}", l_endian);
                let mut switch_endian;
                if buf[8] as char == 'v' {
                    // file stores little endian
                    if !l_endian {
                        switch_endian = true;
                    } else {
                        switch_endian = false;
                    }
                } else {
                    // file stores big endian
                    if l_endian {
                        switch_endian = true;
                    } else {
                        switch_endian = false;
                    }
                }
                println!("switch_endian = {}", switch_endian);
                // get the version number
                let num: &str = header.slice(9, 12); // last 3 chars
                println!("num = {}", num);
                // assumes 64-bit pointers (in file as well as on platform)
                loop {
                    // read_file_dna
                    let io_result = file.read_exact(24); // 4 * int + 64-bit pointer
                    let bhead8 = io_result.unwrap();
                    // pack those 24 bytes into a string ...
                    let mut bhead = String::new();
                    for e in bhead8.iter() {
                        bhead.push(*e as char);
                    }
                    let code: &str = bhead.slice(0, 4); // first 4 chars
                    println!("code = {}", code);
                    let mut len: u32 = 0;
                    len += (bhead8[4] as u32) <<  0;
                    len += (bhead8[5] as u32) <<  8;
                    len += (bhead8[6] as u32) << 16;
                    len += (bhead8[7] as u32) << 24;
                    println!("len = {}", len);
                    if code == "ENDB" && len == 0 {
                        break;
                    } else if code == "DNA1" {
                        // DNA_sdna_from_data
                        let mut counter = 0u32;
                        // SDNA
                        let io_result = file.read_exact(4);
                        let char4 = io_result.unwrap();
                        counter += 4;
                        let mut str4 = String::new();
                        for e in char4.iter() {
                            str4.push(*e as char);
                        }
                        let code: &str = str4.slice(0, 4);
                        println!("  code = {}", code);
                        if code == "SDNA" {
                            // NAME
                            let io_result = file.read_exact(4);
                            let char4 = io_result.unwrap();
                            counter += 4;
                            let mut str4 = String::new();
                            for e in char4.iter() {
                                str4.push(*e as char);
                            }
                            let code: &str = str4.slice(0, 4);
                            println!("  code = {}", code);
                            if code == "NAME" {
                                // nr_names
                                let io_result = file.read_le_u32();
                                let nr_names: u32 = io_result.unwrap();
                                counter += 4;
                                println!("  nr_names = {}", nr_names);
                                let mut nr = 0u32;
                                loop {
                                    let mut name = String::new();
                                    loop {
                                        // expect strings with '\0' as terminator
                                        let io_result = file.read_byte();
                                        let byte: u8 = io_result.unwrap();
                                        counter += 1;
                                        if byte != 0 {
                                            name.push(byte as char);
                                        } else {
                                            println!("    name = '{}'", name);
                                            nr += 1;
                                            break;
                                        }
                                    } // name loop
                                    if nr >= nr_names {
                                        break;
                                    }
                                } // nr_names loop
                                // assume fill bytes with '\0'
                                let mut last_byte;
                                loop {
                                    let io_result = file.read_byte();
                                    let byte: u8 = io_result.unwrap();
                                    counter += 1;
                                    if byte != 0 {
                                        last_byte = byte;
                                        break;
                                    }
                                } // fill bytes
                                // TYPE
                                let io_result = file.read_exact(3);
                                let char3 = io_result.unwrap();
                                counter += 3;
                                let mut str4 = String::new();
                                str4.push(last_byte as char);
                                for e in char3.iter() {
                                    str4.push(*e as char);
                                }
                                let code: &str = str4.slice(0, 4);
                                println!("  code = {}", code);
                                if code == "TYPE" {
                                    // nr_types
                                    let io_result = file.read_le_u32();
                                    let nr_types: u32 = io_result.unwrap();
                                    counter += 4;
                                    println!("  nr_types = {}", nr_types);
                                    let mut nr = 0u32;
                                    loop {
                                        let mut name = String::new();
                                        loop {
                                            // expect strings with
                                            // '\0' as terminator
                                            let io_result = file.read_byte();
                                            let byte: u8 = io_result.unwrap();
                                            counter += 1;
                                            if byte != 0 {
                                                name.push(byte as char);
                                            } else {
                                                println!("    type = '{}'",
                                                         name);
                                                nr += 1;
                                                break;
                                            }
                                        } // type loop
                                        if nr >= nr_types {
                                            break;
                                        }
                                    } // nr_types loop
                                    // assume fill bytes with '\0'
                                    let mut last_byte;
                                    loop {
                                        let io_result = file.read_byte();
                                        let byte: u8 = io_result.unwrap();
                                        counter += 1;
                                        if byte != 0 {
                                            last_byte = byte;
                                            break;
                                        }
                                    } // fill bytes
                                    // TLEN
                                    let io_result = file.read_exact(3);
                                    let char3 = io_result.unwrap();
                                    counter += 3;
                                    let mut str4 = String::new();
                                    str4.push(last_byte as char);
                                    for e in char3.iter() {
                                        str4.push(*e as char);
                                    }
                                    let code: &str = str4.slice(0, 4);
                                    println!("  code = {}", code);
                                    if code == "TLEN" {
                                        // typelens
                                        let io_result = file.read_le_u16();
                                        let typelens: u16 = io_result.unwrap();
                                        counter += 2;
                                        println!("    typelens = {}", typelens);
                                        // skip nr_types times u16 values
                                        let _dummy = file.read_exact((2u32 *
                                                                     nr_types) as
                                                                     usize);
                                        counter += 2u32 * nr_types as u32;
                                        // check next byte
                                        let io_result = file.read_byte();
                                        last_byte = io_result.unwrap();
                                        counter += 1;
                                        if last_byte == 0 {
                                            let io_result = file.read_byte();
                                            last_byte = io_result.unwrap();
                                            counter += 1;
                                        }
                                        // STRC
                                        let io_result = file.read_exact(3);
                                        let char3 = io_result.unwrap();
                                        counter += 3;
                                        let mut str4 = String::new();
                                        str4.push(last_byte as char);
                                        for e in char3.iter() {
                                            str4.push(*e as char);
                                        }
                                        let code: &str = str4.slice(0, 4);
                                        println!("  code = {}", code);
                                        if code == "STRC" {
                                            // nr_structs
                                            let io_result = file.read_le_u32();
                                            let nr_structs: u32 = io_result.unwrap();
                                            counter += 4;
                                            println!("    nr_structs = {}", nr_structs);
                                            nr = 0u32;
                                            loop {
                                                // sp0
                                                let io_result = file.read_le_u16();
                                                let _sp0: u16 = io_result.unwrap();
                                                counter += 2;
                                                // sp1
                                                let io_result = file.read_le_u16();
                                                let sp1: u16 = io_result.unwrap();
                                                counter += 2;
                                                for _n in range(0u16, 2 * sp1) {
                                                    let io_result = file.read_le_u16();
                                                    let _u: u16 = io_result.unwrap();
                                                    counter += 2;
                                                }
                                                nr += 1;
                                                if nr >= nr_structs {
                                                    break;
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        // read remaining stuff
                        println!("skip {} bytes", len - counter);
                        let _dummy = file.read_exact((len - counter) as usize);
                    } else {
                        let tc: &str = bhead.slice(0, 2); // first 2 chars
                        if tc == "CA" {
                            let mut counter = 0u32;
                            // struct ID (see DNA_ID.h)
                            let _next = file.read_le_u64();
                            counter += 8;
                            let _prev = file.read_le_u64();
                            counter += 8;
                            let _newid = file.read_le_u64();
                            counter += 8;
                            let _lib = file.read_le_u64();
                            counter += 8;
                            let io_result = file.read_exact(66);
                            let bname = io_result.unwrap();
                            // pack those 66 bytes into a string ...
                            let mut name = String::new();
                            for e in bname.iter() {
                                if *e == 0u8 {
                                    // ... but stop as soon as you see '\0'
                                    break;
                                } else {
                                    name.push(*e as char);
                                }
                            }
                            counter += 66;
                            let _flag = file.read_le_u16();
                            counter += 2;
                            let _us = file.read_le_u32();
                            counter += 4;
                            let _icon_id = file.read_le_u32();
                            counter += 4;
                            let _pad2 = file.read_le_u32();
                            counter += 4;
                            let _properties = file.read_le_u64();
                            counter += 8;
                            // struct Camera (see DNA_camera_types.h)
                            let _adt = file.read_le_u64();
                            counter += 8;
                            let io_result = file.read_u8();
                            let cam_type: u8 = io_result.unwrap();
                            counter += 1;
                            let _dtx = file.read_u8();
                            counter += 1;
                            let _flag = file.read_le_u16();
                            counter += 2;
                            let _passepartalpha = file.read_le_f32();
                            counter += 4;
                            let _clipsta = file.read_le_f32();
                            counter += 4;
                            let _clipend = file.read_le_f32();
                            counter += 4;
                            let io_result = file.read_le_f32();
                            let lens: f32 = io_result.unwrap();
                            counter += 4;
                            let _dummy = file.read_exact((len - counter) as usize);
                            if cam_type == 0u8 {
                                println!("Camera({}, {}, {})", name, "CAM_PERSP", lens)
                            } else {
                                println!("Camera({}, {}, {})", name, cam_type, lens)
                            }
                        } else {
                            let _dummy = file.read_exact(len as usize);
                        }
                    }
                }
            } else {
                println!("ERROR: not a Blender file.");
            }
        } // file gets closed here
    }
}
<|endoftext|>


<commit_before>use raft::client::RaftClient;
use super::DEFAULT_SERVICE_ID;
use super::heartbeat_rpc::*;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::{thread, time};
use bifrost_hasher::hash_str;

static PING_INTERVAL: u64 = 500; //5 secs for 500ms heartbeat

pub struct MemberService {
    raft_client: Arc<RaftClient>,
    address: String,
    closed: AtomicBool,
    id: u64,
}

impl MemberService {
    pub fn new(server_address: String, raft_client: &Arc<RaftClient>) -> Arc<MemberService> {
        let service = Arc::new(MemberService {
            raft_client:  raft_client.clone(),
            address: server_address.clone(),
            closed: AtomicBool::new(false),
            id: hash_str(server_address),
        });
        let service_clone = service.clone();
        thread::spawn(move || {
            while !service_clone.closed.load(Ordering::Relaxed) {
                let rpc_client = service_clone.raft_client.current_leader_rpc_client();
                if let Some(rpc_client) = rpc_client {
                    let heartbeat_client = SyncServiceClient::new(DEFAULT_SERVICE_ID, rpc_client);
                    heartbeat_client.ping(service_clone.id);
                }
                thread::sleep(time::Duration::from_millis(PING_INTERVAL))
            }
        });
        return service;
    }
    pub fn close(&self) {
        self.closed.store(true, Ordering::Relaxed);
    }
}

<commit_msg>join and leave for member in MemberService<commit_after>use raft::client::RaftClient;
use super::DEFAULT_SERVICE_ID;
use super::heartbeat_rpc::*;
use super::raft::client::SMClient;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::{thread, time};
use bifrost_hasher::hash_str;

static PING_INTERVAL: u64 = 500; //5 secs for 500ms heartbeat

pub struct MemberService {
    pub sm_client: Arc<SMClient>,
    raft_client: Arc<RaftClient>,
    address: String,
    closed: AtomicBool,
    id: u64,
}

impl MemberService {
    pub fn new(server_address: String, raft_client: &Arc<RaftClient>) -> Arc<MemberService> {
        let sm_client = Arc::new(SMClient::new(DEFAULT_SERVICE_ID, &raft_client));
        let service = Arc::new(MemberService {
            sm_client: sm_client.clone(),
            raft_client:  raft_client.clone(),
            address: server_address.clone(),
            closed: AtomicBool::new(false),
            id: hash_str(server_address.clone()),
        });
        sm_client.join(server_address);
        let service_clone = service.clone();
        thread::spawn(move || {
            while !service_clone.closed.load(Ordering::Relaxed) {
                let rpc_client = service_clone.raft_client.current_leader_rpc_client();
                if let Some(rpc_client) = rpc_client {
                    let heartbeat_client = SyncServiceClient::new(DEFAULT_SERVICE_ID, rpc_client);
                    heartbeat_client.ping(service_clone.id);
                }
                thread::sleep(time::Duration::from_millis(PING_INTERVAL))
            }
        });
        return service;
    }
    pub fn close(&self) {
        self.closed.store(true, Ordering::Relaxed);
    }
    pub fn leave(&self) {
        self.sm_client.leave(self.id);
        self.close();
    }
}

<|endoftext|>


<commit_before>use std;
use libc::c_void;

use execstate::ExecState;
use trap::Trap;

use self::ucontext::ucontext_t;
use self::ucontext_reg::*;

mod ucontext;
mod ucontext_reg;

pub fn read_execstate(uc: *const c_void) -> ExecState {
    let mut es : ExecState = unsafe { std::mem::uninitialized() };

    unsafe {
        let uc = uc as *mut ucontext_t;
        let mc = &(*uc).uc_mcontext;

        es.pc = mc.gregs[REG_RIP] as usize;
        es.sp = mc.gregs[REG_RSP] as usize;
        es.ra = 0;

        for i in 0..es.regs.len() {
            es.regs[i] = mc.gregs[i] as usize;
        }
    }

    es
}

pub fn write_execstate(es: ExecState, uc: *const c_void) {
    unsafe {
        let uc = uc as *mut ucontext_t;
        let mc = &mut (*uc).uc_mcontext;

        mc.gregs[REG_RIP] = es.pc as i64;
        mc.gregs[REG_RSP] = es.sp as i64;

        for i in 0..es.regs.len() {
            mc.gregs[i] = es.regs[i] as i64;
        }
    }
}

pub fn detect_trap(signo: i32, es: &ExecState) -> Option<Trap> {
    None
}
<commit_msg>signal: write/read registers with right indices<commit_after>use std;
use libc::c_void;

use execstate::ExecState;
use trap::Trap;

use self::ucontext::ucontext_t;
use self::ucontext_reg::*;

mod ucontext;
mod ucontext_reg;

pub fn read_execstate(uc: *const c_void) -> ExecState {
    let mut es : ExecState = unsafe { std::mem::uninitialized() };

    unsafe {
        let uc = uc as *mut ucontext_t;
        let mc = &(*uc).uc_mcontext;

        es.pc = mc.gregs[REG_RIP] as usize;
        es.sp = mc.gregs[REG_RSP] as usize;
        es.ra = 0;

        for i in 0..es.regs.len() {
            let src = reg2ucontext(i);
            let dest = i;

            es.regs[dest] = mc.gregs[src] as usize;
        }
    }

    es
}

pub fn write_execstate(es: ExecState, uc: *const c_void) {
    unsafe {
        let uc = uc as *mut ucontext_t;
        let mc = &mut (*uc).uc_mcontext;

        mc.gregs[REG_RIP] = es.pc as i64;
        mc.gregs[REG_RSP] = es.sp as i64;

        for i in 0..es.regs.len() {
            let src = i;
            let dest = reg2ucontext(i);

            mc.gregs[dest] = es.regs[src] as i64;
        }
    }
}

/// Dora uses same index for register as CPU,
// but the indices in mcontext are different and need to be mapped
fn reg2ucontext(reg: usize) -> usize {
    match reg {
        0 => REG_RAX,
        1 => REG_RCX,
        2 => REG_RDX,
        3 => REG_RBX,
        4 => REG_RSP,
        5 => REG_RBP,
        6 => REG_RSI,
        7 => REG_RDI,
        8 => REG_R8,
        9 => REG_R9,
        10 => REG_R10,
        11 => REG_R11,
        12 => REG_R12,
        13 => REG_R13,
        14 => REG_R14,
        15 => REG_R15,
        _ => unreachable!()
    }
}

pub fn detect_trap(signo: i32, es: &ExecState) -> Option<Trap> {
    None
}
<|endoftext|>


<commit_before>//! Tests for future-incompat-report messages

use cargo_test_support::registry::Package;
use cargo_test_support::{basic_manifest, is_nightly, project, Project};

// An arbitrary lint (array_into_iter) that triggers a report.
const FUTURE_EXAMPLE: &'static str = "fn main() { [true].into_iter(); }";
// Some text that will be displayed when the lint fires.
const FUTURE_OUTPUT: &'static str = "[..]array_into_iter[..]";

fn simple_project() -> Project {
    project()
        .file("Cargo.toml", &basic_manifest("foo", "0.0.0"))
        .file("src/main.rs", FUTURE_EXAMPLE)
        .build()
}

#[cargo_test]
fn no_output_on_stable() {
    let p = simple_project();

    p.cargo("build")
        .with_stderr_contains(FUTURE_OUTPUT)
        .with_stderr_does_not_contain("[..]cargo report[..]")
        .run();
}

#[cargo_test]
fn gate_future_incompat_report() {
    let p = simple_project();

    p.cargo("build --future-incompat-report")
        .with_stderr_contains("error: the `--future-incompat-report` flag is unstable[..]")
        .with_status(101)
        .run();

    // Both `-Z future-incompat-report` and `-Z unstable-opts` are required
    p.cargo("build --future-incompat-report -Z future-incompat-report")
        .masquerade_as_nightly_cargo()
        .with_stderr_contains("error: the `--future-incompat-report` flag is unstable[..]")
        .with_status(101)
        .run();

    p.cargo("build --future-incompat-report -Z unstable-options")
        .masquerade_as_nightly_cargo()
        .with_stderr_contains(
            "error: Usage of `--future-incompat-report` requires `-Z future-incompat-report`",
        )
        .with_status(101)
        .run();

    p.cargo("report future-incompatibilities --id foo")
        .with_stderr_contains("error: `cargo report` can only be used on the nightly channel")
        .with_status(101)
        .run();
}

#[cargo_test]
fn test_zero_future_incompat() {
    if !is_nightly() {
        return;
    }

    let p = project()
        .file("Cargo.toml", &basic_manifest("foo", "0.0.0"))
        .file("src/main.rs", "fn main() {}")
        .build();

    // No note if --future-incompat-report is not specified.
    p.cargo("build -Z future-incompat-report")
        .masquerade_as_nightly_cargo()
        .with_stderr(
            "\
[COMPILING] foo v0.0.0 [..]
[FINISHED] [..]
",
        )
        .run();

    p.cargo("build --future-incompat-report -Z unstable-options -Z future-incompat-report")
        .masquerade_as_nightly_cargo()
        .with_stderr(
            "\
[FINISHED] [..]
note: 0 dependencies had future-incompatible warnings
",
        )
        .run();
}

#[cargo_test]
fn test_single_crate() {
    if !is_nightly() {
        return;
    }

    let p = simple_project();

    for command in &["build", "check", "rustc", "test"] {
        p.cargo(command).arg("-Zfuture-incompat-report")
            .masquerade_as_nightly_cargo()
            .with_stderr_contains(FUTURE_OUTPUT)
            .with_stderr_contains("warning: the following packages contain code that will be rejected by a future version of Rust: foo v0.0.0 [..]")
            .with_stderr_does_not_contain("[..]incompatibility[..]")
            .run();

        p.cargo(command).arg("-Zfuture-incompat-report").arg("-Zunstable-options").arg("--future-incompat-report")
            .masquerade_as_nightly_cargo()
            .with_stderr_contains(FUTURE_OUTPUT)
            .with_stderr_contains("warning: the following packages contain code that will be rejected by a future version of Rust: foo v0.0.0 [..]")
            .with_stderr_contains("The package `foo v0.0.0 ([..])` currently triggers the following future incompatibility lints:")
            .run();
    }
}

#[cargo_test]
fn test_multi_crate() {
    if !is_nightly() {
        return;
    }

    Package::new("first-dep", "0.0.1")
        .file("src/lib.rs", FUTURE_EXAMPLE)
        .publish();
    Package::new("second-dep", "0.0.2")
        .file("src/lib.rs", FUTURE_EXAMPLE)
        .publish();

    let p = project()
        .file(
            "Cargo.toml",
            r#"
                [package]
                name = "foo"
                version = "0.0.0"

                [dependencies]
                first-dep = "*"
                second-dep = "*"
              "#,
        )
        .file("src/main.rs", "fn main() {}")
        .build();

    for command in &["build", "check", "rustc", "test"] {
        p.cargo(command).arg("-Zfuture-incompat-report")
            .masquerade_as_nightly_cargo()
            .with_stderr_does_not_contain(FUTURE_OUTPUT)
            .with_stderr_contains("warning: the following packages contain code that will be rejected by a future version of Rust: first-dep v0.0.1, second-dep v0.0.2")
            // Check that we don't have the 'triggers' message shown at the bottom of this loop
            .with_stderr_does_not_contain("[..]triggers[..]")
            .run();

        p.cargo(command).arg("-Zunstable-options").arg("-Zfuture-incompat-report").arg("--future-incompat-report")
            .masquerade_as_nightly_cargo()
            .with_stderr_contains("warning: the following packages contain code that will be rejected by a future version of Rust: first-dep v0.0.1, second-dep v0.0.2")
            .with_stderr_contains("The package `first-dep v0.0.1` currently triggers the following future incompatibility lints:")
            .with_stderr_contains("The package `second-dep v0.0.2` currently triggers the following future incompatibility lints:")
            .run();
    }

    // Test that passing the correct id via '--id' doesn't generate a warning message
    let output = p
        .cargo("build -Z future-incompat-report")
        .masquerade_as_nightly_cargo()
        .exec_with_output()
        .unwrap();

    // Extract the 'id' from the stdout. We are looking
    // for the id in a line of the form "run `cargo report future-incompatibilities --id yZ7S`"
    // which is generated by Cargo to tell the user what command to run
    // This is just to test that passing the id suppresses the warning mesasge. Any users needing
    // access to the report from a shell script should use the `--future-incompat-report` flag
    let stderr = std::str::from_utf8(&output.stderr).unwrap();

    // Find '--id <ID>' in the output
    let mut iter = stderr.split(' ');
    iter.find(|w| *w == "--id").unwrap();
    let id = iter
        .next()
        .unwrap_or_else(|| panic!("Unexpected output:\n{}", stderr));
    // Strip off the trailing '`' included in the output
    let id: String = id.chars().take_while(|c| *c != '`').collect();

    p.cargo(&format!("report future-incompatibilities -Z future-incompat-report --id {}", id))
        .masquerade_as_nightly_cargo()
        .with_stdout_contains("The package `first-dep v0.0.1` currently triggers the following future incompatibility lints:")
        .with_stdout_contains("The package `second-dep v0.0.2` currently triggers the following future incompatibility lints:")
        .run();

    // Test without --id, and also the full output of the report.
    let output = p
        .cargo("report future-incompat -Z future-incompat-report")
        .masquerade_as_nightly_cargo()
        .exec_with_output()
        .unwrap();
    let output = std::str::from_utf8(&output.stdout).unwrap();
    assert!(output.starts_with("The following warnings were discovered"));
    let mut lines = output
        .lines()
        // Skip the beginning of the per-package information.
        .skip_while(|line| !line.starts_with("The package"));
    for expected in &["first-dep v0.0.1", "second-dep v0.0.2"] {
        assert_eq!(
            &format!(
                "The package `{}` currently triggers the following future incompatibility lints:",
                expected
            ),
            lines.next().unwrap()
        );
        let mut count = 0;
        while let Some(line) = lines.next() {
            if line.is_empty() {
                break;
            }
            count += 1;
        }
        assert!(count > 0);
    }
    assert_eq!(lines.next(), None);
}

#[cargo_test]
fn color() {
    if !is_nightly() {
        return;
    }

    let p = simple_project();

    p.cargo("check -Zfuture-incompat-report")
        .masquerade_as_nightly_cargo()
        .run();

    p.cargo("report future-incompatibilities -Z future-incompat-report")
        .masquerade_as_nightly_cargo()
        .with_stdout_does_not_contain("[..]\x1b[[..]")
        .run();

    p.cargo("report future-incompatibilities -Z future-incompat-report")
        .masquerade_as_nightly_cargo()
        .env("CARGO_TERM_COLOR", "always")
        .with_stdout_contains("[..]\x1b[[..]")
        .run();
}

#[cargo_test]
fn bad_ids() {
    if !is_nightly() {
        return;
    }

    let p = simple_project();

    p.cargo("report future-incompatibilities -Z future-incompat-report --id 1")
        .masquerade_as_nightly_cargo()
        .with_status(101)
        .with_stderr("error: no reports are currently available")
        .run();

    p.cargo("check -Zfuture-incompat-report")
        .masquerade_as_nightly_cargo()
        .run();

    p.cargo("report future-incompatibilities -Z future-incompat-report --id foo")
        .masquerade_as_nightly_cargo()
        .with_status(1)
        .with_stderr("error: Invalid value: could not parse `foo` as a number")
        .run();

    p.cargo("report future-incompatibilities -Z future-incompat-report --id 7")
        .masquerade_as_nightly_cargo()
        .with_status(101)
        .with_stderr(
            "\
error: could not find report with ID 7
Available IDs are: 1
",
        )
        .run();
}

#[cargo_test]
fn suggestions_for_updates() {
    if !is_nightly() {
        return;
    }

    Package::new("with_updates", "1.0.0")
        .file("src/lib.rs", FUTURE_EXAMPLE)
        .publish();
    Package::new("big_update", "1.0.0")
        .file("src/lib.rs", FUTURE_EXAMPLE)
        .publish();
    Package::new("without_updates", "1.0.0")
        .file("src/lib.rs", FUTURE_EXAMPLE)
        .publish();

    let p = project()
        .file(
            "Cargo.toml",
            r#"
                [package]
                name = "foo"
                version = "0.1.0"

                [dependencies]
                with_updates = "1"
                big_update = "1"
                without_updates = "1"
            "#,
        )
        .file("src/lib.rs", "")
        .build();

    p.cargo("generate-lockfile").run();

    Package::new("with_updates", "1.0.1")
        .file("src/lib.rs", "")
        .publish();
    Package::new("with_updates", "1.0.2")
        .file("src/lib.rs", "")
        .publish();
    Package::new("big_update", "2.0.0")
        .file("src/lib.rs", "")
        .publish();

    // This is a hack to force cargo to update the index. Cargo can't do this
    // automatically because doing a network update on every build would be a
    // bad idea. Under normal circumstances, we'll hope the user has done
    // something else along the way to trigger an update (building some other
    // project or something). This could use some more consideration of how to
    // handle this better (maybe only trigger an update if it hasn't updated
    // in a long while?).
    p.cargo("update -p without_updates").run();

    p.cargo("check -Zfuture-incompat-report")
        .masquerade_as_nightly_cargo()
        .with_stderr_contains("[..]cargo report future-incompatibilities --id 1[..]")
        .run();

    p.cargo("report future-incompatibilities")
        .masquerade_as_nightly_cargo()
        .with_stdout_contains(
            "\
The following packages appear to have newer versions available.
You may want to consider updating them to a newer version to see if the issue has been fixed.

big_update v1.0.0 has the following newer versions available: 2.0.0
with_updates v1.0.0 has the following newer versions available: 1.0.1, 1.0.2
",
        )
        .run();
}
<commit_msg>Auto merge of #9638 - ehuss:ignore-future_incompat, r=alexcrichton<commit_after>//! Tests for future-incompat-report messages

use cargo_test_support::registry::Package;
use cargo_test_support::{basic_manifest, is_nightly, project, Project};

// An arbitrary lint (array_into_iter) that triggers a report.
const FUTURE_EXAMPLE: &'static str = "fn main() { [true].into_iter(); }";
// Some text that will be displayed when the lint fires.
const FUTURE_OUTPUT: &'static str = "[..]array_into_iter[..]";

fn simple_project() -> Project {
    project()
        .file("Cargo.toml", &basic_manifest("foo", "0.0.0"))
        .file("src/main.rs", FUTURE_EXAMPLE)
        .build()
}

#[cargo_test]
fn no_output_on_stable() {
    let p = simple_project();

    p.cargo("build")
        .with_stderr_contains(FUTURE_OUTPUT)
        .with_stderr_does_not_contain("[..]cargo report[..]")
        .run();
}

#[cargo_test]
fn gate_future_incompat_report() {
    let p = simple_project();

    p.cargo("build --future-incompat-report")
        .with_stderr_contains("error: the `--future-incompat-report` flag is unstable[..]")
        .with_status(101)
        .run();

    // Both `-Z future-incompat-report` and `-Z unstable-opts` are required
    p.cargo("build --future-incompat-report -Z future-incompat-report")
        .masquerade_as_nightly_cargo()
        .with_stderr_contains("error: the `--future-incompat-report` flag is unstable[..]")
        .with_status(101)
        .run();

    p.cargo("build --future-incompat-report -Z unstable-options")
        .masquerade_as_nightly_cargo()
        .with_stderr_contains(
            "error: Usage of `--future-incompat-report` requires `-Z future-incompat-report`",
        )
        .with_status(101)
        .run();

    p.cargo("report future-incompatibilities --id foo")
        .with_stderr_contains("error: `cargo report` can only be used on the nightly channel")
        .with_status(101)
        .run();
}

#[cargo_test]
fn test_zero_future_incompat() {
    if !is_nightly() {
        return;
    }

    let p = project()
        .file("Cargo.toml", &basic_manifest("foo", "0.0.0"))
        .file("src/main.rs", "fn main() {}")
        .build();

    // No note if --future-incompat-report is not specified.
    p.cargo("build -Z future-incompat-report")
        .masquerade_as_nightly_cargo()
        .with_stderr(
            "\
[COMPILING] foo v0.0.0 [..]
[FINISHED] [..]
",
        )
        .run();

    p.cargo("build --future-incompat-report -Z unstable-options -Z future-incompat-report")
        .masquerade_as_nightly_cargo()
        .with_stderr(
            "\
[FINISHED] [..]
note: 0 dependencies had future-incompatible warnings
",
        )
        .run();
}

#[cargo_test]
#[ignore] // Waiting on https://github.com/rust-lang/rust/pull/86478
fn test_single_crate() {
    if !is_nightly() {
        return;
    }

    let p = simple_project();

    for command in &["build", "check", "rustc", "test"] {
        p.cargo(command).arg("-Zfuture-incompat-report")
            .masquerade_as_nightly_cargo()
            .with_stderr_contains(FUTURE_OUTPUT)
            .with_stderr_contains("warning: the following packages contain code that will be rejected by a future version of Rust: foo v0.0.0 [..]")
            .with_stderr_does_not_contain("[..]incompatibility[..]")
            .run();

        p.cargo(command).arg("-Zfuture-incompat-report").arg("-Zunstable-options").arg("--future-incompat-report")
            .masquerade_as_nightly_cargo()
            .with_stderr_contains(FUTURE_OUTPUT)
            .with_stderr_contains("warning: the following packages contain code that will be rejected by a future version of Rust: foo v0.0.0 [..]")
            .with_stderr_contains("The package `foo v0.0.0 ([..])` currently triggers the following future incompatibility lints:")
            .run();
    }
}

#[cargo_test]
#[ignore] // Waiting on https://github.com/rust-lang/rust/pull/86478
fn test_multi_crate() {
    if !is_nightly() {
        return;
    }

    Package::new("first-dep", "0.0.1")
        .file("src/lib.rs", FUTURE_EXAMPLE)
        .publish();
    Package::new("second-dep", "0.0.2")
        .file("src/lib.rs", FUTURE_EXAMPLE)
        .publish();

    let p = project()
        .file(
            "Cargo.toml",
            r#"
                [package]
                name = "foo"
                version = "0.0.0"

                [dependencies]
                first-dep = "*"
                second-dep = "*"
              "#,
        )
        .file("src/main.rs", "fn main() {}")
        .build();

    for command in &["build", "check", "rustc", "test"] {
        p.cargo(command).arg("-Zfuture-incompat-report")
            .masquerade_as_nightly_cargo()
            .with_stderr_does_not_contain(FUTURE_OUTPUT)
            .with_stderr_contains("warning: the following packages contain code that will be rejected by a future version of Rust: first-dep v0.0.1, second-dep v0.0.2")
            // Check that we don't have the 'triggers' message shown at the bottom of this loop
            .with_stderr_does_not_contain("[..]triggers[..]")
            .run();

        p.cargo(command).arg("-Zunstable-options").arg("-Zfuture-incompat-report").arg("--future-incompat-report")
            .masquerade_as_nightly_cargo()
            .with_stderr_contains("warning: the following packages contain code that will be rejected by a future version of Rust: first-dep v0.0.1, second-dep v0.0.2")
            .with_stderr_contains("The package `first-dep v0.0.1` currently triggers the following future incompatibility lints:")
            .with_stderr_contains("The package `second-dep v0.0.2` currently triggers the following future incompatibility lints:")
            .run();
    }

    // Test that passing the correct id via '--id' doesn't generate a warning message
    let output = p
        .cargo("build -Z future-incompat-report")
        .masquerade_as_nightly_cargo()
        .exec_with_output()
        .unwrap();

    // Extract the 'id' from the stdout. We are looking
    // for the id in a line of the form "run `cargo report future-incompatibilities --id yZ7S`"
    // which is generated by Cargo to tell the user what command to run
    // This is just to test that passing the id suppresses the warning mesasge. Any users needing
    // access to the report from a shell script should use the `--future-incompat-report` flag
    let stderr = std::str::from_utf8(&output.stderr).unwrap();

    // Find '--id <ID>' in the output
    let mut iter = stderr.split(' ');
    iter.find(|w| *w == "--id").unwrap();
    let id = iter
        .next()
        .unwrap_or_else(|| panic!("Unexpected output:\n{}", stderr));
    // Strip off the trailing '`' included in the output
    let id: String = id.chars().take_while(|c| *c != '`').collect();

    p.cargo(&format!("report future-incompatibilities -Z future-incompat-report --id {}", id))
        .masquerade_as_nightly_cargo()
        .with_stdout_contains("The package `first-dep v0.0.1` currently triggers the following future incompatibility lints:")
        .with_stdout_contains("The package `second-dep v0.0.2` currently triggers the following future incompatibility lints:")
        .run();

    // Test without --id, and also the full output of the report.
    let output = p
        .cargo("report future-incompat -Z future-incompat-report")
        .masquerade_as_nightly_cargo()
        .exec_with_output()
        .unwrap();
    let output = std::str::from_utf8(&output.stdout).unwrap();
    assert!(output.starts_with("The following warnings were discovered"));
    let mut lines = output
        .lines()
        // Skip the beginning of the per-package information.
        .skip_while(|line| !line.starts_with("The package"));
    for expected in &["first-dep v0.0.1", "second-dep v0.0.2"] {
        assert_eq!(
            &format!(
                "The package `{}` currently triggers the following future incompatibility lints:",
                expected
            ),
            lines.next().unwrap()
        );
        let mut count = 0;
        while let Some(line) = lines.next() {
            if line.is_empty() {
                break;
            }
            count += 1;
        }
        assert!(count > 0);
    }
    assert_eq!(lines.next(), None);
}

#[cargo_test]
#[ignore] // Waiting on https://github.com/rust-lang/rust/pull/86478
fn color() {
    if !is_nightly() {
        return;
    }

    let p = simple_project();

    p.cargo("check -Zfuture-incompat-report")
        .masquerade_as_nightly_cargo()
        .run();

    p.cargo("report future-incompatibilities -Z future-incompat-report")
        .masquerade_as_nightly_cargo()
        .with_stdout_does_not_contain("[..]\x1b[[..]")
        .run();

    p.cargo("report future-incompatibilities -Z future-incompat-report")
        .masquerade_as_nightly_cargo()
        .env("CARGO_TERM_COLOR", "always")
        .with_stdout_contains("[..]\x1b[[..]")
        .run();
}

#[cargo_test]
#[ignore] // Waiting on https://github.com/rust-lang/rust/pull/86478
fn bad_ids() {
    if !is_nightly() {
        return;
    }

    let p = simple_project();

    p.cargo("report future-incompatibilities -Z future-incompat-report --id 1")
        .masquerade_as_nightly_cargo()
        .with_status(101)
        .with_stderr("error: no reports are currently available")
        .run();

    p.cargo("check -Zfuture-incompat-report")
        .masquerade_as_nightly_cargo()
        .run();

    p.cargo("report future-incompatibilities -Z future-incompat-report --id foo")
        .masquerade_as_nightly_cargo()
        .with_status(1)
        .with_stderr("error: Invalid value: could not parse `foo` as a number")
        .run();

    p.cargo("report future-incompatibilities -Z future-incompat-report --id 7")
        .masquerade_as_nightly_cargo()
        .with_status(101)
        .with_stderr(
            "\
error: could not find report with ID 7
Available IDs are: 1
",
        )
        .run();
}

#[cargo_test]
#[ignore] // Waiting on https://github.com/rust-lang/rust/pull/86478
fn suggestions_for_updates() {
    if !is_nightly() {
        return;
    }

    Package::new("with_updates", "1.0.0")
        .file("src/lib.rs", FUTURE_EXAMPLE)
        .publish();
    Package::new("big_update", "1.0.0")
        .file("src/lib.rs", FUTURE_EXAMPLE)
        .publish();
    Package::new("without_updates", "1.0.0")
        .file("src/lib.rs", FUTURE_EXAMPLE)
        .publish();

    let p = project()
        .file(
            "Cargo.toml",
            r#"
                [package]
                name = "foo"
                version = "0.1.0"

                [dependencies]
                with_updates = "1"
                big_update = "1"
                without_updates = "1"
            "#,
        )
        .file("src/lib.rs", "")
        .build();

    p.cargo("generate-lockfile").run();

    Package::new("with_updates", "1.0.1")
        .file("src/lib.rs", "")
        .publish();
    Package::new("with_updates", "1.0.2")
        .file("src/lib.rs", "")
        .publish();
    Package::new("big_update", "2.0.0")
        .file("src/lib.rs", "")
        .publish();

    // This is a hack to force cargo to update the index. Cargo can't do this
    // automatically because doing a network update on every build would be a
    // bad idea. Under normal circumstances, we'll hope the user has done
    // something else along the way to trigger an update (building some other
    // project or something). This could use some more consideration of how to
    // handle this better (maybe only trigger an update if it hasn't updated
    // in a long while?).
    p.cargo("update -p without_updates").run();

    p.cargo("check -Zfuture-incompat-report")
        .masquerade_as_nightly_cargo()
        .with_stderr_contains("[..]cargo report future-incompatibilities --id 1[..]")
        .run();

    p.cargo("report future-incompatibilities")
        .masquerade_as_nightly_cargo()
        .with_stdout_contains(
            "\
The following packages appear to have newer versions available.
You may want to consider updating them to a newer version to see if the issue has been fixed.

big_update v1.0.0 has the following newer versions available: 2.0.0
with_updates v1.0.0 has the following newer versions available: 1.0.1, 1.0.2
",
        )
        .run();
}
<|endoftext|>


<commit_before>//! Describe pattern type

///  cairo_pattern_type_t is used to describe the type of a given pattern.
///
/// The type of a pattern is determined by the function used to create it. The cairo_pattern_create_rgb() and cairo_pattern_create_rgba() functions create SOLID patterns. The remaining cairo_pattern_create functions map to pattern types in obvious ways.
///
/// The pattern type can be queried with cairo_pattern_get_type()
///
/// Most cairo_pattern_t functions can be called with a pattern of any type, (though trying to change the extend or filter for a solid pattern will have no effect). A notable exception is cairo_pattern_add_color_stop_rgb() and cairo_pattern_add_color_stop_rgba() which must only be called with gradient patterns (either LINEAR or RADIAL). Otherwise the pattern will be shutdown and put into an error state.
///
/// New entries may be added in future versions.
///
/// Since 1.2
#[repr(i32)]
pub enum PatternType {
  /// The pattern is a solid (uniform) color. It may be opaque or translucent, since 1.2.
  Solid = 0,
  /// The pattern is a based on a surface (an image), since 1.2.
  Surface = 1,
  /// The pattern is a linear gradient, since 1.2.
  Linear = 2,
  /// The pattern is a radial gradient, since 1.2.
  Radial = 3,
  /// The pattern is a mesh, since 1.12.
  Mesh = 4,
  /// The pattern is a user pattern providing raster data, since 1.12.
  RasterSource = 5
}
<commit_msg>Replaced Cairo '_t' types with Rust-Cairo types<commit_after>//! Describe pattern type

/// pattern::pattern_type::PatternType is used to describe the type of a given pattern.
///
/// The type of a pattern is determined by the function used to create it. The cairo_pattern_create_rgb() and cairo_pattern_create_rgba() functions create SOLID patterns. The remaining cairo_pattern_create functions map to pattern types in obvious ways.
///
/// The pattern type can be queried with cairo_pattern_get_type()
///
/// Most pattern::Pattern functions can be called with a pattern of any type, (though trying to change the extend or filter for a solid pattern will have no effect). A notable exception is cairo_pattern_add_color_stop_rgb() and cairo_pattern_add_color_stop_rgba() which must only be called with gradient patterns (either LINEAR or RADIAL). Otherwise the pattern will be shutdown and put into an error state.
///
/// New entries may be added in future versions.
///
/// Since 1.2
#[repr(i32)]
pub enum PatternType {
  /// The pattern is a solid (uniform) color. It may be opaque or translucent, since 1.2.
  Solid = 0,
  /// The pattern is a based on a surface (an image), since 1.2.
  Surface = 1,
  /// The pattern is a linear gradient, since 1.2.
  Linear = 2,
  /// The pattern is a radial gradient, since 1.2.
  Radial = 3,
  /// The pattern is a mesh, since 1.12.
  Mesh = 4,
  /// The pattern is a user pattern providing raster data, since 1.12.
  RasterSource = 5
}
<|endoftext|>


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

<%namespace name="helpers" file="/helpers.mako.rs" />

<% data.new_style_struct("Column", inherited=False) %>

${helpers.predefined_type(
    "column-width",
    "length::NonNegativeLengthOrAuto",
    "Either::Second(Auto)",
    initial_specified_value="Either::Second(Auto)",
    extra_prefixes="moz",
    animation_value_type="NonNegativeLengthOrAuto",
    servo_pref="layout.columns.enabled",
    spec="https://drafts.csswg.org/css-multicol/#propdef-column-width",
    servo_restyle_damage="rebuild_and_reflow",
)}

${helpers.predefined_type(
    "column-count",
    "ColumnCount",
    "computed::ColumnCount::auto()",
    initial_specified_value="specified::ColumnCount::auto()",
    servo_pref="layout.columns.enabled",
    animation_value_type="AnimatedColumnCount",
    extra_prefixes="moz",
    spec="https://drafts.csswg.org/css-multicol/#propdef-column-count",
    servo_restyle_damage="rebuild_and_reflow",
)}

${helpers.single_keyword(
    "column-fill",
    "balance auto",
    extra_prefixes="moz",
    products="gecko",
    animation_value_type="discrete",
    gecko_enum_prefix="StyleColumnFill",
    spec="https://drafts.csswg.org/css-multicol/#propdef-column-fill",
)}

${helpers.predefined_type(
    "column-rule-width",
    "BorderSideWidth",
    "crate::values::computed::NonNegativeLength::new(3.)",
    initial_specified_value="specified::BorderSideWidth::Medium",
    computed_type="crate::values::computed::NonNegativeLength",
    products="gecko",
    spec="https://drafts.csswg.org/css-multicol/#propdef-column-rule-width",
    animation_value_type="NonNegativeLength",
    extra_prefixes="moz",
)}

// https://drafts.csswg.org/css-multicol-1/#crc
${helpers.predefined_type(
    "column-rule-color",
    "Color",
    "computed_value::T::currentcolor()",
    initial_specified_value="specified::Color::currentcolor()",
    products="gecko",
    animation_value_type="AnimatedColor",
    extra_prefixes="moz",
    ignored_when_colors_disabled=True,
    spec="https://drafts.csswg.org/css-multicol/#propdef-column-rule-color",
)}

${helpers.single_keyword(
    "column-span",
    "none all",
    products="gecko",
    animation_value_type="discrete",
    gecko_enum_prefix="StyleColumnSpan",
    gecko_pref="layout.css.column-span.enabled",
    spec="https://drafts.csswg.org/css-multicol/#propdef-column-span",
    extra_prefixes="moz:layout.css.column-span.enabled",
)}

${helpers.single_keyword(
    "column-rule-style",
    "none hidden dotted dashed solid double groove ridge inset outset",
    products="gecko",
    extra_prefixes="moz",
    gecko_constant_prefix="NS_STYLE_BORDER_STYLE",
    animation_value_type="discrete",
    spec="https://drafts.csswg.org/css-multicol/#propdef-column-rule-style",
)}
<commit_msg>style: Enable CSS column-span in UA stylesheet, and update test expectations.<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

<%namespace name="helpers" file="/helpers.mako.rs" />

<% data.new_style_struct("Column", inherited=False) %>

${helpers.predefined_type(
    "column-width",
    "length::NonNegativeLengthOrAuto",
    "Either::Second(Auto)",
    initial_specified_value="Either::Second(Auto)",
    extra_prefixes="moz",
    animation_value_type="NonNegativeLengthOrAuto",
    servo_pref="layout.columns.enabled",
    spec="https://drafts.csswg.org/css-multicol/#propdef-column-width",
    servo_restyle_damage="rebuild_and_reflow",
)}

${helpers.predefined_type(
    "column-count",
    "ColumnCount",
    "computed::ColumnCount::auto()",
    initial_specified_value="specified::ColumnCount::auto()",
    servo_pref="layout.columns.enabled",
    animation_value_type="AnimatedColumnCount",
    extra_prefixes="moz",
    spec="https://drafts.csswg.org/css-multicol/#propdef-column-count",
    servo_restyle_damage="rebuild_and_reflow",
)}

${helpers.single_keyword(
    "column-fill",
    "balance auto",
    extra_prefixes="moz",
    products="gecko",
    animation_value_type="discrete",
    gecko_enum_prefix="StyleColumnFill",
    spec="https://drafts.csswg.org/css-multicol/#propdef-column-fill",
)}

${helpers.predefined_type(
    "column-rule-width",
    "BorderSideWidth",
    "crate::values::computed::NonNegativeLength::new(3.)",
    initial_specified_value="specified::BorderSideWidth::Medium",
    computed_type="crate::values::computed::NonNegativeLength",
    products="gecko",
    spec="https://drafts.csswg.org/css-multicol/#propdef-column-rule-width",
    animation_value_type="NonNegativeLength",
    extra_prefixes="moz",
)}

// https://drafts.csswg.org/css-multicol-1/#crc
${helpers.predefined_type(
    "column-rule-color",
    "Color",
    "computed_value::T::currentcolor()",
    initial_specified_value="specified::Color::currentcolor()",
    products="gecko",
    animation_value_type="AnimatedColor",
    extra_prefixes="moz",
    ignored_when_colors_disabled=True,
    spec="https://drafts.csswg.org/css-multicol/#propdef-column-rule-color",
)}

// FIXME: Remove enabled_in="ua" once column-span is enabled on nightly (bug 1423383).
${helpers.single_keyword(
    "column-span",
    "none all",
    products="gecko",
    animation_value_type="discrete",
    gecko_enum_prefix="StyleColumnSpan",
    gecko_pref="layout.css.column-span.enabled",
    enabled_in="ua",
    spec="https://drafts.csswg.org/css-multicol/#propdef-column-span",
    extra_prefixes="moz:layout.css.column-span.enabled",
)}

${helpers.single_keyword(
    "column-rule-style",
    "none hidden dotted dashed solid double groove ridge inset outset",
    products="gecko",
    extra_prefixes="moz",
    gecko_constant_prefix="NS_STYLE_BORDER_STYLE",
    animation_value_type="discrete",
    spec="https://drafts.csswg.org/css-multicol/#propdef-column-rule-style",
)}
<|endoftext|>


<commit_before>extern crate glium;
extern crate calx_color;
extern crate calx_system;
extern crate calx_window;
extern crate cgmath;
extern crate collision;

use calx_window::{WindowBuilder, Event, Key, Window};
use calx_color::{SRgba, Rgba};
use collision::Intersect;
use cgmath::{EuclideanVector, Matrix, Point};

struct Frame {
    pub pixels: Vec<u32>,
}

impl Frame {
    pub fn new() -> Frame {
        let mut pixels = Vec::with_capacity(640 * 360);
        pixels.resize(640 * 360, 0x00000000);
        Frame {
            pixels: pixels
        }
    }

    pub fn blit(self, window: &mut Window) {
        window.set_frame(glium::texture::RawImage2d::from_raw_rgba(self.pixels, (640, 360)));
    }
}

fn main() {
    let mut window = WindowBuilder::new().set_title("Voxel demo").build();
    let mut tick = 0;

    loop {
        for e in window.events().into_iter() {
            match e {
                Event::Quit => return,
                Event::KeyPress(Key::Escape) => return,
                Event::KeyPress(Key::F12) => {
                    calx_system::save_screenshot("calx", window.screenshot())
                        .unwrap();
                }
                _ => (),
            }
        }

        let projection = cgmath::Matrix4::from(
            cgmath::PerspectiveFov {
                fovy: cgmath::deg(45.0),
                aspect: 640.0 / 380.0, // XXX: Hardcoding
                near: 0.1,
                far: 1024.0,
            });

        let a = (tick as f32) / 96.0;
        let modelview: cgmath::Matrix4<f32> =
            cgmath::Matrix4::look_at(cgmath::Point3::new(15.0 * a.sin() +
                                                         16.0,
                                                         15.0 * a.cos() +
                                                         16.0,
                                                         16.0),
                                     cgmath::Point3::new(0.0, 0.0, 0.0),
                                     cgmath::vec3(0.0, 0.0, 1.0));

        let mut frame = Frame::new();

        let orb = collision::Sphere {
            center: cgmath::Point3::new(0.0, 20.0, 0.0),
            radius: 1.0,
        };

        for y in 0..360 {
            for x in 0..640 {
                let u = (x as f32 - 320.0) / 320.0;
                let v = (y as f32 - 180.0) / 180.0;

                let ray = collision::Ray::new(
                        cgmath::Point3::new(0.0, 0.0, 0.0),
                        projection./*mul_m(&modelview).*/mul_v(cgmath::vec4(u, 1.0, v, 1.0)).truncate().normalize());

                if let Some(p) = (orb, ray).intersection() {
                    let normal = p.sub_p(orb.center).normalize();
                    let mut n = cgmath::dot(normal, cgmath::vec3(-1.0, -1.0, -1.0).normalize());
                    if n < 0.1 {
                        n = 0.1;
                    }
                    let c: SRgba = Rgba::new(n, n, 0.0, 0.0).into();
                    frame.pixels[x + 640 * y] = ((c.a as u32) << 24) + ((c.b as u32) << 16) + ((c.g as u32) << 8) + c.r as u32;
                }

                //println!("{:?}", projection * cgmath::vec4(u, 1.0, v, 1.0));
            }
        }

        frame.blit(&mut window);

        window.end_frame();

        tick += 1;
    }
}
<commit_msg>Raytrace demo<commit_after>extern crate glium;
extern crate calx_color;
extern crate calx_system;
extern crate calx_window;
extern crate cgmath;
extern crate collision;

use calx_window::{WindowBuilder, Event, Key, Window};
use calx_color::{SRgba, Rgba};
use collision::Intersect;
use cgmath::{EuclideanVector, Matrix, Point};

struct Frame {
    pub pixels: Vec<u32>,
}

impl Frame {
    pub fn new() -> Frame {
        let mut pixels = Vec::with_capacity(320 * 180);
        pixels.resize(320 * 180, 0x00000000);
        Frame {
            pixels: pixels
        }
    }

    pub fn blit(self, window: &mut Window) {
        window.set_frame(glium::texture::RawImage2d::from_raw_rgba(self.pixels, (320, 180)));
    }
}

fn main() {
    let mut window = WindowBuilder::new().set_size([320, 180]).set_title("Voxel demo").build();
    let mut tick = 0;

    loop {
        for e in window.events().into_iter() {
            match e {
                Event::Quit => return,
                Event::KeyPress(Key::Escape) => return,
                Event::KeyPress(Key::F12) => {
                    calx_system::save_screenshot("calx", window.screenshot())
                        .unwrap();
                }
                _ => (),
            }
        }

        let projection = cgmath::Matrix4::from(
            cgmath::PerspectiveFov {
                fovy: cgmath::deg(45.0),
                aspect: 16.0 / 9.0, // XXX: Hardcoding
                near: 0.1,
                far: 1024.0,
            });

        /*
        let a = (tick as f32) / 96.0;
        let eye =  cgmath::Point3::new(15.0 * a.sin(),
            -15.0 * a.cos(),
            0.0);
            */
        let eye = cgmath::Point3::new(0.0, -20.0, 0.0);
        let modelview: cgmath::Matrix4<f32> =
            cgmath::Matrix4::look_at(
                    eye,
                    cgmath::Point3::new(0.0, 0.0, 0.0),
                    cgmath::vec3(0.0, 0.0, 1.0));

        let mut frame = Frame::new();

        let orb = collision::Sphere {
            center: cgmath::Point3::new(0.0, 0.0, 0.0),
            radius: 1.0,
        };

        for y in 0..180 {
            for x in 0..320 {
                let u = (x as f32 - 160.0) / 160.0;
                let v = -(y as f32 - 90.0) / 90.0;

                let ray = collision::Ray::new(
                        eye,
                        projection.mul_m(&modelview).mul_v(cgmath::vec4(u, v, 1.0, 0.0)).truncate().normalize());

                if let Some(p) = (orb, ray).intersection() {
                    let normal = p.sub_p(orb.center).normalize();
                    let mut n = cgmath::dot(normal, cgmath::vec3(-1.0, -1.0, -1.0).normalize());
                    if n < 0.1 {
                        n = 0.1;
                    }
                    let c: SRgba = Rgba::new(n, n, 0.0, 0.0).into();
                    frame.pixels[x + 320 * y] = ((c.a as u32) << 24) + ((c.b as u32) << 16) + ((c.g as u32) << 8) + c.r as u32;
                }
            }
        }

        frame.blit(&mut window);

        window.end_frame();

        tick += 1;
    }
}
<|endoftext|>