<commit_before>/* io::mod.rs */

use core::mem::volatile_store;
use kernel::sgash;

mod font;

/* http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0225d/BBABEGGE.html */
pub static UART0: *mut u32 = 0x101f1000 as *mut u32;

pub static UART0_IMSC: *mut u32 = (0x101f1000 + 0x038) as *mut u32;
#[allow(dead_code)]
pub static VIC_INTENABLE: *mut u32 = (0x10140000 + 0x010) as *mut u32;

pub static mut CURSOR_X: u32 = 0;
pub static mut CURSOR_Y: u32 = 0;
pub static CURSOR_HEIGHT: u32 = 16;
pub static CURSOR_WIDTH: u32 = 8;
pub static mut CURSOR_COLOR: u32 = 0x000000FF;
pub static mut FG_COLOR: u32 = 0x00FFFFFF;
pub static mut BG_COLOR: u32 = 0xF0000000;
pub static mut CURSOR_BUFFER: [u32, ..8*16] = [0x00FF0000, ..8*16];
pub static mut SAVE_X: u32 = 0;
pub static mut SAVE_Y: u32 = 0;
pub static START_ADDR: u32 = 1024*1024;
pub static mut SCREEN_WIDTH: u32 = 0;
pub static mut SCREEN_HEIGHT: u32 = 0;

pub unsafe fn init(width: u32, height: u32)
{
	SCREEN_WIDTH = width;
	SCREEN_HEIGHT= height;
	sgash::init();

	/* For the following magic values, see
	 * http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0225d/CACHEDGD.html
	 */

	// 800x600
	// See http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0225d/CACCCFBF.html
	if (SCREEN_WIDTH == 800 && SCREEN_HEIGHT == 600)
	{
		ws(0x10000010, 0x2CAC);
		ws(0x10120000, 0x1313A4C4);
		ws(0x10120004, 0x0505F657);
		ws(0x10120008, 0x071F1800);

	/* See http://forum.osdev.org/viewtopic.php?p=195000 */
	ws(0x10120010, START_ADDR);

	/* See http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.ddi0161e/I911024.html */
	ws(0x10120018, 0x82B);
	}

	// 640x480
	// See http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0225d/CACCCFBF.html
	else if (SCREEN_WIDTH == 640 && SCREEN_HEIGHT == 480)
	{
	ws(0x10000010, 0x2C77);
	ws(0x10120000, 0x3F1F3F9C);
	ws(0x10120004, 0x090B61DF);
	ws(0x10120008, 0x067F1800);

	/* See http://forum.osdev.org/viewtopic.php?p=195000 */
	ws(0x10120010, START_ADDR);

	/* See http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.ddi0161e/I911024.html */
	ws(0x10120018, 0x82B);

	}
	set_bg(0x222C38);
	set_fg(0xFAFCFF);
	set_cursor_color(0xFAFCFF);
	fill_bg();
	sgash::drawstr(&"sgash> ");
	draw_cursor();
}

pub unsafe fn write_char(c: char, address: *mut u32) {
	volatile_store(address, c as u32);
}

pub unsafe fn scrollup()
{
	let mut i = CURSOR_HEIGHT*SCREEN_WIDTH;
	while i < (SCREEN_WIDTH*SCREEN_HEIGHT)
	{
	*((START_ADDR + ((i-16*SCREEN_WIDTH)*4)) as *mut u32) = *((START_ADDR+(i*4)) as *u32);
	i += 1;
	}
	i = 4*(SCREEN_WIDTH*SCREEN_HEIGHT - CURSOR_HEIGHT*SCREEN_WIDTH);
	while i < 4*SCREEN_WIDTH*SCREEN_HEIGHT
	{
	*((START_ADDR + (i as u32)) as *mut u32) = BG_COLOR;
	i += 4;
	}
	CURSOR_X = 0x0u32;
	CURSOR_Y -= CURSOR_HEIGHT;
}
pub unsafe fn draw_char(c: char)
{
	if CURSOR_X+(SCREEN_WIDTH*CURSOR_Y) >= SCREEN_WIDTH*SCREEN_HEIGHT
	{
	scrollup();
	}
	let font_offset = (c as u8) - 0x20;
	let map = font::bitmaps[font_offset];

	let mut i = -1;
	let mut j = 0;
	let mut addr = START_ADDR + 4*(CURSOR_X + CURSOR_WIDTH + 1 + SCREEN_WIDTH*CURSOR_Y);
	while j < CURSOR_HEIGHT {
		while i < CURSOR_WIDTH {
			//let addr = START_ADDR + 4*(CURSOR_X + CURSOR_WIDTH - i + SCREEN_WIDTH*(CURSOR_Y + j));
			//let addr = START_ADDR + 4*(CURSOR_X + CURSOR_WIDTH + SCREEN_WIDTH*CURSOR_Y) - 4*i + 4*SCREEN_WIDTH*j
			if ((map[j] >> 4*i) & 1) == 1 {
				*(addr as *mut u32) = FG_COLOR;
			}
			else {
				*(addr as *mut u32) = BG_COLOR;
			}

			addr-= 4;
			i += 1;
		}
		addr += 4*(i+SCREEN_WIDTH);
		i = 0;
		j += 1;
	}
}

pub unsafe fn backup()
{
	let mut i = 0;
	let mut j = 0;
	while j < CURSOR_HEIGHT
	{
	while i < CURSOR_WIDTH
	{
		let addr = START_ADDR + 4*(CURSOR_X + i + SCREEN_WIDTH*(CURSOR_Y + j));
		CURSOR_BUFFER[i + j*8] = *(addr as *mut u32);
		i += 1;
	}
	i = 0;
	j += 1;
	}
	SAVE_X = CURSOR_X;
	SAVE_Y = CURSOR_Y;
}

pub unsafe fn restore()
{
	let mut i = 0;
	let mut j = 0;
	while j < CURSOR_HEIGHT
	{
	while i < CURSOR_WIDTH
	{
		let addr = START_ADDR + 4*(SAVE_X + i + SCREEN_WIDTH*(SAVE_Y + j));
		*(addr as *mut u32) = CURSOR_BUFFER[i + j*8];
		i += 1;
	}
	i = 0;
	j += 1;
	}
}

pub unsafe fn draw_cursor()
{

	let mut i = 0;
	let mut j = 0;

	while j < CURSOR_HEIGHT
	{
	while i < CURSOR_WIDTH
	{
		let addr = START_ADDR + 4*(CURSOR_X + i + SCREEN_WIDTH*(CURSOR_Y + j));
		*(addr as *mut u32) = CURSOR_COLOR;
		i += 1;
	}
	i = 0;
	j += 1;
	}

}

pub unsafe fn paint(color: u32)
{
	let mut i = 0;
	while i < SCREEN_WIDTH*SCREEN_HEIGHT
	{
	*((START_ADDR as u32 + i*4) as *mut u32) = color;
	i+=1;
	}
}

pub unsafe fn fill_bg()
{
	paint(BG_COLOR);
}

#[allow(dead_code)]
pub unsafe fn read(addr: u32)	->	u32
{
	*(addr as *mut u32)
}

pub unsafe fn ws(addr: u32, value: u32)
{
	*(addr as *mut u32) = *(addr as *mut u32) | value;
}

#[allow(dead_code)]
pub unsafe fn wh(addr: u32, value: u32)
{
	*(addr as *mut u32) = value;
}

pub unsafe fn set_fg(color: u32)
{
	FG_COLOR = color;
}

pub unsafe fn set_bg(color: u32)
{
	BG_COLOR = color;
}

pub unsafe fn set_cursor_color(color: u32)
{
	CURSOR_COLOR = color;
}
<commit_msg>Fixed some MORE tabbing in mod.rs<commit_after>/* io::mod.rs */

use core::mem::volatile_store;
use kernel::sgash;

mod font;

/* http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0225d/BBABEGGE.html */
pub static UART0: *mut u32 = 0x101f1000 as *mut u32;

pub static UART0_IMSC: *mut u32 = (0x101f1000 + 0x038) as *mut u32;
#[allow(dead_code)]
pub static VIC_INTENABLE: *mut u32 = (0x10140000 + 0x010) as *mut u32;

pub static mut CURSOR_X: u32 = 0;
pub static mut CURSOR_Y: u32 = 0;
pub static CURSOR_HEIGHT: u32 = 16;
pub static CURSOR_WIDTH: u32 = 8;
pub static mut CURSOR_COLOR: u32 = 0x000000FF;
pub static mut FG_COLOR: u32 = 0x00FFFFFF;
pub static mut BG_COLOR: u32 = 0xF0000000;
pub static mut CURSOR_BUFFER: [u32, ..8*16] = [0x00FF0000, ..8*16];
pub static mut SAVE_X: u32 = 0;
pub static mut SAVE_Y: u32 = 0;
pub static START_ADDR: u32 = 1024*1024;
pub static mut SCREEN_WIDTH: u32 = 0;
pub static mut SCREEN_HEIGHT: u32 = 0;

pub unsafe fn init(width: u32, height: u32)
{
	SCREEN_WIDTH = width;
	SCREEN_HEIGHT= height;
	sgash::init();

	/* For the following magic values, see
	 * http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0225d/CACHEDGD.html
	 */

	// 800x600
	// See http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0225d/CACCCFBF.html
	if (SCREEN_WIDTH == 800 && SCREEN_HEIGHT == 600) {
		ws(0x10000010, 0x2CAC);
		ws(0x10120000, 0x1313A4C4);
		ws(0x10120004, 0x0505F657);
		ws(0x10120008, 0x071F1800);

		/* See http://forum.osdev.org/viewtopic.php?p=195000 */
		ws(0x10120010, START_ADDR);

		/* See http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.ddi0161e/I911024.html */
		ws(0x10120018, 0x82B);
	}

	// 640x480
	// See http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0225d/CACCCFBF.html
	else if (SCREEN_WIDTH == 640 && SCREEN_HEIGHT == 480) {
		ws(0x10000010, 0x2C77);
		ws(0x10120000, 0x3F1F3F9C);
		ws(0x10120004, 0x090B61DF);
		ws(0x10120008, 0x067F1800);

		/* See http://forum.osdev.org/viewtopic.php?p=195000 */
		ws(0x10120010, START_ADDR);

		/* See http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.ddi0161e/I911024.html */
		ws(0x10120018, 0x82B);
	}
	set_bg(0x222C38);
	set_fg(0xFAFCFF);
	set_cursor_color(0xFAFCFF);
	fill_bg();
	sgash::drawstr(&"sgash> ");
	draw_cursor();
}

pub unsafe fn write_char(c: char, address: *mut u32) {
	volatile_store(address, c as u32);
}

pub unsafe fn scrollup()
{
	let mut i = CURSOR_HEIGHT*SCREEN_WIDTH;
	while i < (SCREEN_WIDTH*SCREEN_HEIGHT) {
		*((START_ADDR + ((i-16*SCREEN_WIDTH)*4)) as *mut u32) = *((START_ADDR+(i*4)) as *u32);
		i += 1;
	}
	i = 4*(SCREEN_WIDTH*SCREEN_HEIGHT - CURSOR_HEIGHT*SCREEN_WIDTH);
	while i < 4*SCREEN_WIDTH*SCREEN_HEIGHT {
		*((START_ADDR + (i as u32)) as *mut u32) = BG_COLOR;
		i += 4;
	}
	CURSOR_X = 0x0u32;
	CURSOR_Y -= CURSOR_HEIGHT;
}
pub unsafe fn draw_char(c: char)
{
	if CURSOR_X+(SCREEN_WIDTH*CURSOR_Y) >= SCREEN_WIDTH*SCREEN_HEIGHT
	{
	scrollup();
	}
	let font_offset = (c as u8) - 0x20;
	let map = font::bitmaps[font_offset];

	let mut i = -1;
	let mut j = 0;
	let mut addr = START_ADDR + 4*(CURSOR_X + CURSOR_WIDTH + 1 + SCREEN_WIDTH*CURSOR_Y);
	while j < CURSOR_HEIGHT {
		while i < CURSOR_WIDTH {
			//let addr = START_ADDR + 4*(CURSOR_X + CURSOR_WIDTH - i + SCREEN_WIDTH*(CURSOR_Y + j));
			//let addr = START_ADDR + 4*(CURSOR_X + CURSOR_WIDTH + SCREEN_WIDTH*CURSOR_Y) - 4*i + 4*SCREEN_WIDTH*j
			if ((map[j] >> 4*i) & 1) == 1 {
				*(addr as *mut u32) = FG_COLOR;
			}
			else {
				*(addr as *mut u32) = BG_COLOR;
			}

			addr-= 4;
			i += 1;
		}
		addr += 4*(i+SCREEN_WIDTH);
		i = 0;
		j += 1;
	}
}

pub unsafe fn backup()
{
	let mut i = 0;
	let mut j = 0;
	while j < CURSOR_HEIGHT
	{
		while i < CURSOR_WIDTH
		{
			let addr = START_ADDR + 4*(CURSOR_X + i + SCREEN_WIDTH*(CURSOR_Y + j));
			CURSOR_BUFFER[i + j*8] = *(addr as *mut u32);
			i += 1;
		}
		i = 0;
		j += 1;
	}
	SAVE_X = CURSOR_X;
	SAVE_Y = CURSOR_Y;
}

pub unsafe fn restore()
{
	let mut i = 0;
	let mut j = 0;
	while j < CURSOR_HEIGHT
	{
		while i < CURSOR_WIDTH
		{
			let addr = START_ADDR + 4*(SAVE_X + i + SCREEN_WIDTH*(SAVE_Y + j));
			*(addr as *mut u32) = CURSOR_BUFFER[i + j*8];
			i += 1;
		}
		i = 0;
		j += 1;
	}
}

pub unsafe fn draw_cursor()
{

	let mut i = 0;
	let mut j = 0;

	while j < CURSOR_HEIGHT
	{
		while i < CURSOR_WIDTH
		{
			let addr = START_ADDR + 4*(CURSOR_X + i + SCREEN_WIDTH*(CURSOR_Y + j));
			*(addr as *mut u32) = CURSOR_COLOR;
			i += 1;
		}
		i = 0;
		j += 1;
	}

}

pub unsafe fn paint(color: u32)
{
	let mut i = 0;
	while i < SCREEN_WIDTH*SCREEN_HEIGHT
	{
		*((START_ADDR as u32 + i*4) as *mut u32) = color;
		i+=1;
	}
}

pub unsafe fn fill_bg()
{
	paint(BG_COLOR);
}

#[allow(dead_code)]
pub unsafe fn read(addr: u32)	->	u32
{
	*(addr as *mut u32)
}

pub unsafe fn ws(addr: u32, value: u32)
{
	*(addr as *mut u32) = *(addr as *mut u32) | value;
}

#[allow(dead_code)]
pub unsafe fn wh(addr: u32, value: u32)
{
	*(addr as *mut u32) = value;
}

pub unsafe fn set_fg(color: u32)
{
	FG_COLOR = color;
}

pub unsafe fn set_bg(color: u32)
{
	BG_COLOR = color;
}

pub unsafe fn set_cursor_color(color: u32)
{
	CURSOR_COLOR = color;
}
<|endoftext|>


<commit_before>extern crate editdistancewf as wf;

#[cfg(test)]
mod basic_distances {
    use wf;

    #[test]
    pub fn two_identical_sequences_have_a_distance_of_zero () {
        let left  = "left";
        let right = "right";

        assert_eq!(wf::distance(left.chars(), right.chars()), 0)
    }
}
<commit_msg>(red) we do not actually calculate a difference<commit_after>extern crate editdistancewf as wf;

#[cfg(test)]
mod basic_distances {
    use wf;

    #[test]
    pub fn two_identical_sequences_have_a_distance_of_zero () {
        let left  = "left";
        let right = "right";

        assert_eq!(wf::distance(left.chars(), right.chars()), 0)
    }

    #[test]
    pub fn simple_differences () {
        assert_eq!(wf::distance("left".chars(), "lend".chars()), 2)
    }
}
<|endoftext|>


<commit_before>extern crate quote;
extern crate syn;

mod features;

#[macro_use]
mod macros;

use quote::quote;
use syn::{Data, DeriveInput};

#[test]
fn test_unit() {
    let code = quote! {
        struct Unit;
    };

    snapshot!(code as DeriveInput);
}

#[test]
fn test_struct() {
    let code = quote! {
        #[derive(Debug, Clone)]
        pub struct Item {
            pub ident: Ident,
            pub attrs: Vec<Attribute>
        }
    };

    let actual = snapshot!(code as DeriveInput);

    snapshot!(actual.attrs[0].interpret_meta().unwrap());
}

#[test]
fn test_union() {
    let code = quote! {
        union MaybeUninit<T> {
            uninit: (),
            value: T
        }
    };

    snapshot!(code as DeriveInput);
}

#[test]
#[cfg(feature = "full")]
fn test_enum() {
    let code = quote! {
        /// See the std::result module documentation for details.
        #[must_use]
        pub enum Result<T, E> {
            Ok(T),
            Err(E),
            Surprise = 0isize,

            // Smuggling data into a proc_macro_derive,
            // in the style of https://github.com/dtolnay/proc-macro-hack
            ProcMacroHack = (0, "data").0
        }
    };

    let actual = snapshot!(code as DeriveInput);

    let meta_items: Vec<_> = actual
        .attrs
        .into_iter()
        .map(|attr| attr.interpret_meta().unwrap())
        .collect();

    snapshot!(meta_items);
}

#[test]
fn test_attr_with_path() {
    let code = quote! {
        #[::attr_args::identity
            fn main() { assert_eq!(foo(), "Hello, world!"); }]
        struct Dummy;
    };

    let actual = snapshot!(code as DeriveInput);

    assert!(actual.attrs[0].interpret_meta().is_none());
}

#[test]
fn test_attr_with_non_mod_style_path() {
    let code = quote! {
        #[inert <T>]
        struct S;
    };

    let actual = snapshot!(code as DeriveInput);

    assert!(actual.attrs[0].interpret_meta().is_none());
}

#[test]
fn test_attr_with_mod_style_path_with_self() {
    let code = quote! {
        #[foo::self]
        struct S;
    };

    let actual = snapshot!(code as DeriveInput);

    assert!(actual.attrs[0].interpret_meta().is_none());
}

#[test]
fn test_pub_restricted() {
    // Taken from tests/rust/src/test/ui/resolve/auxiliary/privacy-struct-ctor.rs
    let code = quote! {
        pub(in m) struct Z(pub(in m::n) u8);
    };

    snapshot!(code as DeriveInput);
}

#[test]
fn test_vis_crate() {
    let code = quote! {
        crate struct S;
    };

    snapshot!(code as DeriveInput);
}

#[test]
fn test_pub_restricted_crate() {
    let code = quote! {
        pub(crate) struct S;
    };

    snapshot!(code as DeriveInput);
}

#[test]
fn test_pub_restricted_super() {
    let code = quote! {
        pub(super) struct S;
    };

    snapshot!(code as DeriveInput);
}

#[test]
fn test_pub_restricted_in_super() {
    let code = quote! {
        pub(in super) struct S;
    };

    snapshot!(code as DeriveInput);
}

#[test]
fn test_fields_on_unit_struct() {
    let code = quote! {
        struct S;
    };

    let actual = snapshot!(code as DeriveInput);

    match actual.data {
        Data::Struct(data) => {
            assert_eq!(0, data.fields.iter().count());
        }
        _ => panic!("expected a struct"),
    }
}

#[test]
fn test_fields_on_named_struct() {
    let code = quote! {
        struct S {
            foo: i32,
            pub bar: String,
        }
    };

    let actual = snapshot!(code as DeriveInput);

    match actual.data {
        Data::Struct(data) => {
            snapshot!(data.fields.iter().collect::<Vec<_>>());
        }
        _ => panic!("expected a struct"),
    }
}

#[test]
fn test_fields_on_tuple_struct() {
    let code = quote! {
        struct S(i32, pub String);
    };

    let actual = snapshot!(code as DeriveInput);

    match actual.data {
        Data::Struct(data) => {
            snapshot!(data.fields.iter().collect::<Vec<_>>());
        }
        _ => panic!("expected a struct"),
    }
}

#[test]
fn test_ambiguous_crate() {
    let code = quote! {
        // The field type is `(crate::X)` not `crate (::X)`.
        struct S(crate::X);
    };

    snapshot!(code as DeriveInput);
}
<commit_msg>Change test_derive_input to inline snapshots<commit_after>extern crate quote;
extern crate syn;

mod features;

#[macro_use]
mod macros;

use quote::quote;
use syn::{Data, DeriveInput};

#[test]
fn test_unit() {
    let code = quote! {
        struct Unit;
    };

    snapshot!(code as DeriveInput, @r###"
   ⋮DeriveInput {
   ⋮    attrs: [],
   ⋮    vis: Inherited,
   ⋮    ident: Ident(
   ⋮        Unit,
   ⋮    ),
   ⋮    generics: Generics {
   ⋮        lt_token: None,
   ⋮        params: [],
   ⋮        gt_token: None,
   ⋮        where_clause: None,
   ⋮    },
   ⋮    data: Struct(
   ⋮        DataStruct {
   ⋮            struct_token: Struct,
   ⋮            fields: Unit,
   ⋮            semi_token: Some(
   ⋮                Semi,
   ⋮            ),
   ⋮        },
   ⋮    ),
   ⋮}
    "###);
}

#[test]
fn test_struct() {
    let code = quote! {
        #[derive(Debug, Clone)]
        pub struct Item {
            pub ident: Ident,
            pub attrs: Vec<Attribute>
        }
    };

    let actual = {
        snapshot!(code as DeriveInput, @r###"
       ⋮DeriveInput {
       ⋮    attrs: [
       ⋮        Attribute {
       ⋮            pound_token: Pound,
       ⋮            style: Outer,
       ⋮            bracket_token: Bracket,
       ⋮            path: Path {
       ⋮                leading_colon: None,
       ⋮                segments: [
       ⋮                    PathSegment {
       ⋮                        ident: Ident(
       ⋮                            derive,
       ⋮                        ),
       ⋮                        arguments: None,
       ⋮                    },
       ⋮                ],
       ⋮            },
       ⋮            tts: TokenStream [
       ⋮                Group {
       ⋮                    delimiter: Parenthesis,
       ⋮                    stream: TokenStream [
       ⋮                        Ident {
       ⋮                            sym: Debug,
       ⋮                        },
       ⋮                        Punct {
       ⋮                            op: ',',
       ⋮                            spacing: Alone,
       ⋮                        },
       ⋮                        Ident {
       ⋮                            sym: Clone,
       ⋮                        },
       ⋮                    ],
       ⋮                },
       ⋮            ],
       ⋮        },
       ⋮    ],
       ⋮    vis: Public(
       ⋮        VisPublic {
       ⋮            pub_token: Pub,
       ⋮        },
       ⋮    ),
       ⋮    ident: Ident(
       ⋮        Item,
       ⋮    ),
       ⋮    generics: Generics {
       ⋮        lt_token: None,
       ⋮        params: [],
       ⋮        gt_token: None,
       ⋮        where_clause: None,
       ⋮    },
       ⋮    data: Struct(
       ⋮        DataStruct {
       ⋮            struct_token: Struct,
       ⋮            fields: Named(
       ⋮                FieldsNamed {
       ⋮                    brace_token: Brace,
       ⋮                    named: [
       ⋮                        Field {
       ⋮                            attrs: [],
       ⋮                            vis: Public(
       ⋮                                VisPublic {
       ⋮                                    pub_token: Pub,
       ⋮                                },
       ⋮                            ),
       ⋮                            ident: Some(
       ⋮                                Ident(
       ⋮                                    ident,
       ⋮                                ),
       ⋮                            ),
       ⋮                            colon_token: Some(
       ⋮                                Colon,
       ⋮                            ),
       ⋮                            ty: Path(
       ⋮                                TypePath {
       ⋮                                    qself: None,
       ⋮                                    path: Path {
       ⋮                                        leading_colon: None,
       ⋮                                        segments: [
       ⋮                                            PathSegment {
       ⋮                                                ident: Ident(
       ⋮                                                    Ident,
       ⋮                                                ),
       ⋮                                                arguments: None,
       ⋮                                            },
       ⋮                                        ],
       ⋮                                    },
       ⋮                                },
       ⋮                            ),
       ⋮                        },
       ⋮                        Comma,
       ⋮                        Field {
       ⋮                            attrs: [],
       ⋮                            vis: Public(
       ⋮                                VisPublic {
       ⋮                                    pub_token: Pub,
       ⋮                                },
       ⋮                            ),
       ⋮                            ident: Some(
       ⋮                                Ident(
       ⋮                                    attrs,
       ⋮                                ),
       ⋮                            ),
       ⋮                            colon_token: Some(
       ⋮                                Colon,
       ⋮                            ),
       ⋮                            ty: Path(
       ⋮                                TypePath {
       ⋮                                    qself: None,
       ⋮                                    path: Path {
       ⋮                                        leading_colon: None,
       ⋮                                        segments: [
       ⋮                                            PathSegment {
       ⋮                                                ident: Ident(
       ⋮                                                    Vec,
       ⋮                                                ),
       ⋮                                                arguments: AngleBracketed(
       ⋮                                                    AngleBracketedGenericArguments {
       ⋮                                                        colon2_token: None,
       ⋮                                                        lt_token: Lt,
       ⋮                                                        args: [
       ⋮                                                            Type(
       ⋮                                                                Path(
       ⋮                                                                    TypePath {
       ⋮                                                                        qself: None,
       ⋮                                                                        path: Path {
       ⋮                                                                            leading_colon: None,
       ⋮                                                                            segments: [
       ⋮                                                                                PathSegment {
       ⋮                                                                                ident: Ident(
       ⋮                                                                                Attribute,
       ⋮                                                                                ),
       ⋮                                                                                arguments: None,
       ⋮                                                                                },
       ⋮                                                                            ],
       ⋮                                                                        },
       ⋮                                                                    },
       ⋮                                                                ),
       ⋮                                                            ),
       ⋮                                                        ],
       ⋮                                                        gt_token: Gt,
       ⋮                                                    },
       ⋮                                                ),
       ⋮                                            },
       ⋮                                        ],
       ⋮                                    },
       ⋮                                },
       ⋮                            ),
       ⋮                        },
       ⋮                    ],
       ⋮                },
       ⋮            ),
       ⋮            semi_token: None,
       ⋮        },
       ⋮    ),
       ⋮}
        "###)
    };

    snapshot!(actual.attrs[0].interpret_meta().unwrap(), @r###"
   ⋮List(
   ⋮    MetaList {
   ⋮        ident: Ident(
   ⋮            derive,
   ⋮        ),
   ⋮        paren_token: Paren,
   ⋮        nested: [
   ⋮            Meta(
   ⋮                Word(
   ⋮                    Ident(
   ⋮                        Debug,
   ⋮                    ),
   ⋮                ),
   ⋮            ),
   ⋮            Comma,
   ⋮            Meta(
   ⋮                Word(
   ⋮                    Ident(
   ⋮                        Clone,
   ⋮                    ),
   ⋮                ),
   ⋮            ),
   ⋮        ],
   ⋮    },
   ⋮)
    "###);
}

#[test]
fn test_union() {
    let code = quote! {
        union MaybeUninit<T> {
            uninit: (),
            value: T
        }
    };

    snapshot!(code as DeriveInput);
}

#[test]
#[cfg(feature = "full")]
fn test_enum() {
    let code = quote! {
        /// See the std::result module documentation for details.
        #[must_use]
        pub enum Result<T, E> {
            Ok(T),
            Err(E),
            Surprise = 0isize,

            // Smuggling data into a proc_macro_derive,
            // in the style of https://github.com/dtolnay/proc-macro-hack
            ProcMacroHack = (0, "data").0
        }
    };

    let actual = snapshot!(code as DeriveInput);

    let meta_items: Vec<_> = actual
        .attrs
        .into_iter()
        .map(|attr| attr.interpret_meta().unwrap())
        .collect();

    snapshot!(meta_items);
}

#[test]
fn test_attr_with_path() {
    let code = quote! {
        #[::attr_args::identity
            fn main() { assert_eq!(foo(), "Hello, world!"); }]
        struct Dummy;
    };

    let actual = snapshot!(code as DeriveInput);

    assert!(actual.attrs[0].interpret_meta().is_none());
}

#[test]
fn test_attr_with_non_mod_style_path() {
    let code = quote! {
        #[inert <T>]
        struct S;
    };

    let actual = snapshot!(code as DeriveInput);

    assert!(actual.attrs[0].interpret_meta().is_none());
}

#[test]
fn test_attr_with_mod_style_path_with_self() {
    let code = quote! {
        #[foo::self]
        struct S;
    };

    let actual = snapshot!(code as DeriveInput);

    assert!(actual.attrs[0].interpret_meta().is_none());
}

#[test]
fn test_pub_restricted() {
    // Taken from tests/rust/src/test/ui/resolve/auxiliary/privacy-struct-ctor.rs
    let code = quote! {
        pub(in m) struct Z(pub(in m::n) u8);
    };

    snapshot!(code as DeriveInput);
}

#[test]
fn test_vis_crate() {
    let code = quote! {
        crate struct S;
    };

    snapshot!(code as DeriveInput);
}

#[test]
fn test_pub_restricted_crate() {
    let code = quote! {
        pub(crate) struct S;
    };

    snapshot!(code as DeriveInput);
}

#[test]
fn test_pub_restricted_super() {
    let code = quote! {
        pub(super) struct S;
    };

    snapshot!(code as DeriveInput);
}

#[test]
fn test_pub_restricted_in_super() {
    let code = quote! {
        pub(in super) struct S;
    };

    snapshot!(code as DeriveInput);
}

#[test]
fn test_fields_on_unit_struct() {
    let code = quote! {
        struct S;
    };

    let actual = snapshot!(code as DeriveInput);

    match actual.data {
        Data::Struct(data) => {
            assert_eq!(0, data.fields.iter().count());
        }
        _ => panic!("expected a struct"),
    }
}

#[test]
fn test_fields_on_named_struct() {
    let code = quote! {
        struct S {
            foo: i32,
            pub bar: String,
        }
    };

    let actual = snapshot!(code as DeriveInput);

    match actual.data {
        Data::Struct(data) => {
            snapshot!(data.fields.iter().collect::<Vec<_>>());
        }
        _ => panic!("expected a struct"),
    }
}

#[test]
fn test_fields_on_tuple_struct() {
    let code = quote! {
        struct S(i32, pub String);
    };

    let actual = snapshot!(code as DeriveInput);

    match actual.data {
        Data::Struct(data) => {
            snapshot!(data.fields.iter().collect::<Vec<_>>());
        }
        _ => panic!("expected a struct"),
    }
}

#[test]
fn test_ambiguous_crate() {
    let code = quote! {
        // The field type is `(crate::X)` not `crate (::X)`.
        struct S(crate::X);
    };

    snapshot!(code as DeriveInput);
}
<|endoftext|>


<commit_before>//! This module integrates the buddy heap allocator into the Rust runtime.
use spin::Mutex;
use core::ptr;

use ::Allocator;
use super::{BuddyHeapAllocator, FreeList};

pub const NUM_FREE_LISTS: usize = 19;

static ALLOC: Mutex<Option<BuddyHeapAllocator<'static>>>
    = Mutex::new(None);

static mut KERNEL_FREE_LISTS: [FreeList; NUM_FREE_LISTS]
    // TODO: I really wish there was a less awful way to do this...
    = [ FreeList::new(),  FreeList::new(), FreeList::new()
      , FreeList::new(),  FreeList::new(), FreeList::new()
      , FreeList::new(),  FreeList::new(), FreeList::new()
      , FreeList::new(),  FreeList::new(), FreeList::new()
      , FreeList::new(),  FreeList::new(), FreeList::new()
      , FreeList::new(),  FreeList::new(), FreeList::new()
      , FreeList::new()
      , ];

pub unsafe fn init_heap(start_addr: *mut u8, heap_size: usize ) {
    trace!(target: "alloc", "init_heap() was called.");
    *(ALLOC.lock())
        = Some(BuddyHeapAllocator::new( start_addr
                                      , &mut KERNEL_FREE_LISTS
                                      , heap_size));
}

#[no_mangle]
pub extern "C" fn __rust_allocate(size: usize, align: usize) -> *mut u8 {
    trace!("__rust_allocate() was called.");
    unsafe {
        ALLOC.lock().as_mut()
             .expect("Cannot allocate memory, no system allocator exists!")
             .allocate(size, align)
             .map(|blck| {
                 trace!( target: "alloc"
                       , "__rust_allocate: allocatedd {:?}", blck);
                 blck })
             .unwrap_or(ptr::null_mut())
    }
}

#[no_mangle]
pub extern "C" fn __rust_deallocate( ptr: *mut u8, old_size: usize
                                   , align: usize ) {
    unsafe {
        ALLOC.lock().as_mut()
             .expect("Cannot deallocate memory, no system allocator exists!")
             .deallocate(ptr, old_size, align)
    }
}

#[no_mangle]
pub extern "C" fn __rust_reallocate( ptr: *mut u8, old_size: usize
                                   , size: usize, align: usize )
                                   -> *mut u8 {
    unsafe {
        ALLOC.lock().as_mut()
             .expect("Cannot reallocate memory, no system allocator exists!")
             .reallocate(ptr, old_size, size, align)
             .unwrap_or(ptr::null_mut())
     }
}

/// This is currently unsupported, so we just silently ignore it
/// and return the old size.
#[no_mangle]
pub extern "C" fn __rust_reallocate_inplace( _ptr: *mut u8
                                           , old_size: usize
                                           , _: usize, _: usize )
                                           -> usize {
    old_size
}

#[no_mangle]
pub extern "C" fn __rust_usable_size(size: usize, _: usize) -> usize {
    size
}
<commit_msg>[alloc] re-add old, bad buddy frame allocator code<commit_after>//! This module integrates the buddy heap allocator into the Rust runtime.
use spin::Mutex;
use core::ptr;

use ::{Allocator, FrameAllocator};
use super::{BuddyHeapAllocator, FreeList};

use memory::{ PAddr, PhysicalPage, FrameRange, VAddr };
use memory::arch::PAGE_SIZE;

pub const NUM_FREE_LISTS: usize = 19;

static ALLOC: Mutex<Option<BuddyHeapAllocator<'static>>>
    = Mutex::new(None);

static mut KERNEL_FREE_LISTS: [FreeList; NUM_FREE_LISTS]
    // TODO: I really wish there was a less awful way to do this...
    = [ FreeList::new(),  FreeList::new(), FreeList::new()
      , FreeList::new(),  FreeList::new(), FreeList::new()
      , FreeList::new(),  FreeList::new(), FreeList::new()
      , FreeList::new(),  FreeList::new(), FreeList::new()
      , FreeList::new(),  FreeList::new(), FreeList::new()
      , FreeList::new(),  FreeList::new(), FreeList::new()
      , FreeList::new()
      , ];

pub unsafe fn init_heap(start_addr: *mut u8, heap_size: usize ) {
    trace!(target: "alloc", "init_heap() was called.");
    *(ALLOC.lock())
        = Some(BuddyHeapAllocator::new( start_addr
                                      , &mut KERNEL_FREE_LISTS
                                      , heap_size));
}

// -- integrate the heap allocator into the Rust runtime ------------------
#[no_mangle]
pub extern "C" fn __rust_allocate(size: usize, align: usize) -> *mut u8 {
    trace!("__rust_allocate() was called.");
    unsafe {
        ALLOC.lock().as_mut()
             .expect("Cannot allocate memory, no system allocator exists!")
             .allocate(size, align)
             .map(|blck| {
                 trace!( target: "alloc"
                       , "__rust_allocate: allocatedd {:?}", blck);
                 blck })
             .unwrap_or(ptr::null_mut())
    }
}

#[no_mangle]
pub extern "C" fn __rust_deallocate( ptr: *mut u8, old_size: usize
                                   , align: usize ) {
    unsafe {
        ALLOC.lock().as_mut()
             .expect("Cannot deallocate memory, no system allocator exists!")
             .deallocate(ptr, old_size, align)
    }
}

#[no_mangle]
pub extern "C" fn __rust_reallocate( ptr: *mut u8, old_size: usize
                                   , size: usize, align: usize )
                                   -> *mut u8 {
    unsafe {
        ALLOC.lock().as_mut()
             .expect("Cannot reallocate memory, no system allocator exists!")
             .reallocate(ptr, old_size, size, align)
             .unwrap_or(ptr::null_mut())
     }
}

/// This is currently unsupported, so we just silently ignore it
/// and return the old size.
#[no_mangle]
pub extern "C" fn __rust_reallocate_inplace( _ptr: *mut u8
                                           , old_size: usize
                                           , _: usize, _: usize )
                                           -> usize {
    old_size
}

#[no_mangle]
pub extern "C" fn __rust_usable_size(size: usize, _: usize) -> usize {
    size
}

// quick first pass on using the heap allocator as a frame allocator
// TODO: this is Extremely Bad And Ugly And Awful. pleae make better.
//       – eliza, 1/21/2017
pub struct BuddyFrameAllocator;

impl BuddyFrameAllocator {
    pub const fn new() -> Self { BuddyFrameAllocator }
}

impl FrameAllocator for BuddyFrameAllocator {

    unsafe fn allocate(&self) -> Option<PhysicalPage> {
        ALLOC.lock().as_mut()
             .expect("Cannot allocate frame, no system allocator exists!")
             .allocate(PAGE_SIZE as usize, PAGE_SIZE as usize)
             .map(|block| {
                let addr = VAddr::from_ptr(block);
                // TODO: make this not be bad and ugly.
                PhysicalPage::containing_addr(
                    PAddr::from(addr.as_usize() as u64))
             })

    }

    unsafe fn deallocate(&self, frame: PhysicalPage) {
        ALLOC.lock().as_mut()
             .expect("Cannot deallocate frame, no system allocator exists!")
             .deallocate( frame.as_mut_ptr()
                        , PAGE_SIZE as usize
                        , PAGE_SIZE as usize);

    }

    unsafe fn allocate_range(&self, _num: usize) -> Option<FrameRange> {
        unimplemented!()
    }

    unsafe fn deallocate_range(&self, range: FrameRange) {
        for frame in range {
            ALLOC.lock().as_mut()
                 .expect("Cannot deallocate frames, no system allocator exists")
                 .deallocate( frame.as_mut_ptr()
                            , PAGE_SIZE as usize
                            , PAGE_SIZE as usize);
        }
    }

}
<|endoftext|>


<commit_before>//! Tests for the `cargo rustdoc` command.

use cargo_test_support::{basic_manifest, cross_compile, project};

#[cargo_test]
fn rustdoc_simple() {
    let p = project().file("src/lib.rs", "").build();

    p.cargo("rustdoc -v")
        .with_stderr(
            "\
[DOCUMENTING] foo v0.0.1 ([CWD])
[RUNNING] `rustdoc [..]--crate-name foo src/lib.rs [..]\
        -o [CWD]/target/doc \
        [..] \
        -L dependency=[CWD]/target/debug/deps [..]`
[FINISHED] dev [unoptimized + debuginfo] target(s) in [..]
",
        )
        .run();
}

#[cargo_test]
fn rustdoc_args() {
    let p = project().file("src/lib.rs", "").build();

    p.cargo("rustdoc -v -- --cfg=foo")
        .with_stderr(
            "\
[DOCUMENTING] foo v0.0.1 ([CWD])
[RUNNING] `rustdoc [..]--crate-name foo src/lib.rs [..]\
        -o [CWD]/target/doc \
        [..] \
        --cfg=foo \
        -L dependency=[CWD]/target/debug/deps [..]`
[FINISHED] dev [unoptimized + debuginfo] target(s) in [..]
",
        )
        .run();
}

#[cargo_test]
fn rustdoc_binary_args_passed() {
    let p = project().file("src/main.rs", "").build();

    p.cargo("rustdoc -v")
        .arg("--")
        .arg("--markdown-no-toc")
        .with_stderr_contains("[RUNNING] `rustdoc [..] --markdown-no-toc[..]`")
        .run();
}

#[cargo_test]
fn rustdoc_foo_with_bar_dependency() {
    let foo = project()
        .file(
            "Cargo.toml",
            r#"
                [package]
                name = "foo"
                version = "0.0.1"
                authors = []

                [dependencies.bar]
                path = "../bar"
            "#,
        )
        .file("src/lib.rs", "extern crate bar; pub fn foo() {}")
        .build();
    let _bar = project()
        .at("bar")
        .file("Cargo.toml", &basic_manifest("bar", "0.0.1"))
        .file("src/lib.rs", "pub fn baz() {}")
        .build();

    foo.cargo("rustdoc -v -- --cfg=foo")
        .with_stderr(
            "\
[CHECKING] bar v0.0.1 ([..])
[RUNNING] `rustc [..]bar/src/lib.rs [..]`
[DOCUMENTING] foo v0.0.1 ([CWD])
[RUNNING] `rustdoc [..]--crate-name foo src/lib.rs [..]\
        -o [CWD]/target/doc \
        [..] \
        --cfg=foo \
        -L dependency=[CWD]/target/debug/deps \
        --extern [..]`
[FINISHED] dev [unoptimized + debuginfo] target(s) in [..]
",
        )
        .run();
}

#[cargo_test]
fn rustdoc_only_bar_dependency() {
    let foo = project()
        .file(
            "Cargo.toml",
            r#"
                [package]
                name = "foo"
                version = "0.0.1"
                authors = []

                [dependencies.bar]
                path = "../bar"
            "#,
        )
        .file("src/main.rs", "extern crate bar; fn main() { bar::baz() }")
        .build();
    let _bar = project()
        .at("bar")
        .file("Cargo.toml", &basic_manifest("bar", "0.0.1"))
        .file("src/lib.rs", "pub fn baz() {}")
        .build();

    foo.cargo("rustdoc -v -p bar -- --cfg=foo")
        .with_stderr(
            "\
[DOCUMENTING] bar v0.0.1 ([..])
[RUNNING] `rustdoc [..]--crate-name bar [..]bar/src/lib.rs [..]\
        -o [CWD]/target/doc \
        [..] \
        --cfg=foo \
        -L dependency=[CWD]/target/debug/deps [..]`
[FINISHED] dev [unoptimized + debuginfo] target(s) in [..]
",
        )
        .run();
}

#[cargo_test]
fn rustdoc_same_name_documents_lib() {
    let p = project()
        .file("src/main.rs", "fn main() {}")
        .file("src/lib.rs", r#" "#)
        .build();

    p.cargo("rustdoc -v -- --cfg=foo")
        .with_stderr(
            "\
[DOCUMENTING] foo v0.0.1 ([..])
[RUNNING] `rustdoc [..]--crate-name foo src/lib.rs [..]\
        -o [CWD]/target/doc \
        [..] \
        --cfg=foo \
        -L dependency=[CWD]/target/debug/deps [..]`
[FINISHED] dev [unoptimized + debuginfo] target(s) in [..]
",
        )
        .run();
}

#[cargo_test]
fn features() {
    let p = project()
        .file(
            "Cargo.toml",
            r#"
                [package]
                name = "foo"
                version = "0.0.1"
                authors = []

                [features]
                quux = []
            "#,
        )
        .file("src/lib.rs", "")
        .build();

    p.cargo("rustdoc --verbose --features quux")
        .with_stderr_contains("[..]feature=[..]quux[..]")
        .run();
}

#[cargo_test]
fn proc_macro_crate_type() {
    let p = project()
        .file(
            "Cargo.toml",
            r#"
                [package]
                name = "foo"
                version = "0.0.1"
                authors = []

                [lib]
                proc-macro = true

            "#,
        )
        .file("src/lib.rs", "")
        .build();

    p.cargo("rustdoc --verbose")
        .with_stderr_contains(
            "\
[RUNNING] `rustdoc --crate-type proc-macro [..]`
",
        )
        .run();
}

#[cargo_test]
fn rustdoc_target() {
    if cross_compile::disabled() {
        return;
    }

    let p = project().file("src/lib.rs", "").build();

    p.cargo("rustdoc --verbose --target")
        .arg(cross_compile::alternate())
        .with_stderr(format!(
            "\
[DOCUMENTING] foo v0.0.1 ([..])
[RUNNING] `rustdoc [..]--crate-name foo src/lib.rs [..]\
    --target {target} \
    -o [CWD]/target/{target}/doc \
    [..] \
    -L dependency=[CWD]/target/{target}/debug/deps \
    -L dependency=[CWD]/target/debug/deps[..]`
[FINISHED] dev [unoptimized + debuginfo] target(s) in [..]",
            target = cross_compile::alternate()
        ))
        .run();
}
<commit_msg>test(rustdoc): glob support for package selection<commit_after>//! Tests for the `cargo rustdoc` command.

use cargo_test_support::{basic_manifest, cross_compile, project};

#[cargo_test]
fn rustdoc_simple() {
    let p = project().file("src/lib.rs", "").build();

    p.cargo("rustdoc -v")
        .with_stderr(
            "\
[DOCUMENTING] foo v0.0.1 ([CWD])
[RUNNING] `rustdoc [..]--crate-name foo src/lib.rs [..]\
        -o [CWD]/target/doc \
        [..] \
        -L dependency=[CWD]/target/debug/deps [..]`
[FINISHED] dev [unoptimized + debuginfo] target(s) in [..]
",
        )
        .run();
}

#[cargo_test]
fn rustdoc_args() {
    let p = project().file("src/lib.rs", "").build();

    p.cargo("rustdoc -v -- --cfg=foo")
        .with_stderr(
            "\
[DOCUMENTING] foo v0.0.1 ([CWD])
[RUNNING] `rustdoc [..]--crate-name foo src/lib.rs [..]\
        -o [CWD]/target/doc \
        [..] \
        --cfg=foo \
        -L dependency=[CWD]/target/debug/deps [..]`
[FINISHED] dev [unoptimized + debuginfo] target(s) in [..]
",
        )
        .run();
}

#[cargo_test]
fn rustdoc_binary_args_passed() {
    let p = project().file("src/main.rs", "").build();

    p.cargo("rustdoc -v")
        .arg("--")
        .arg("--markdown-no-toc")
        .with_stderr_contains("[RUNNING] `rustdoc [..] --markdown-no-toc[..]`")
        .run();
}

#[cargo_test]
fn rustdoc_foo_with_bar_dependency() {
    let foo = project()
        .file(
            "Cargo.toml",
            r#"
                [package]
                name = "foo"
                version = "0.0.1"
                authors = []

                [dependencies.bar]
                path = "../bar"
            "#,
        )
        .file("src/lib.rs", "extern crate bar; pub fn foo() {}")
        .build();
    let _bar = project()
        .at("bar")
        .file("Cargo.toml", &basic_manifest("bar", "0.0.1"))
        .file("src/lib.rs", "pub fn baz() {}")
        .build();

    foo.cargo("rustdoc -v -- --cfg=foo")
        .with_stderr(
            "\
[CHECKING] bar v0.0.1 ([..])
[RUNNING] `rustc [..]bar/src/lib.rs [..]`
[DOCUMENTING] foo v0.0.1 ([CWD])
[RUNNING] `rustdoc [..]--crate-name foo src/lib.rs [..]\
        -o [CWD]/target/doc \
        [..] \
        --cfg=foo \
        -L dependency=[CWD]/target/debug/deps \
        --extern [..]`
[FINISHED] dev [unoptimized + debuginfo] target(s) in [..]
",
        )
        .run();
}

#[cargo_test]
fn rustdoc_only_bar_dependency() {
    let foo = project()
        .file(
            "Cargo.toml",
            r#"
                [package]
                name = "foo"
                version = "0.0.1"
                authors = []

                [dependencies.bar]
                path = "../bar"
            "#,
        )
        .file("src/main.rs", "extern crate bar; fn main() { bar::baz() }")
        .build();
    let _bar = project()
        .at("bar")
        .file("Cargo.toml", &basic_manifest("bar", "0.0.1"))
        .file("src/lib.rs", "pub fn baz() {}")
        .build();

    foo.cargo("rustdoc -v -p bar -- --cfg=foo")
        .with_stderr(
            "\
[DOCUMENTING] bar v0.0.1 ([..])
[RUNNING] `rustdoc [..]--crate-name bar [..]bar/src/lib.rs [..]\
        -o [CWD]/target/doc \
        [..] \
        --cfg=foo \
        -L dependency=[CWD]/target/debug/deps [..]`
[FINISHED] dev [unoptimized + debuginfo] target(s) in [..]
",
        )
        .run();
}

#[cargo_test]
fn rustdoc_same_name_documents_lib() {
    let p = project()
        .file("src/main.rs", "fn main() {}")
        .file("src/lib.rs", r#" "#)
        .build();

    p.cargo("rustdoc -v -- --cfg=foo")
        .with_stderr(
            "\
[DOCUMENTING] foo v0.0.1 ([..])
[RUNNING] `rustdoc [..]--crate-name foo src/lib.rs [..]\
        -o [CWD]/target/doc \
        [..] \
        --cfg=foo \
        -L dependency=[CWD]/target/debug/deps [..]`
[FINISHED] dev [unoptimized + debuginfo] target(s) in [..]
",
        )
        .run();
}

#[cargo_test]
fn features() {
    let p = project()
        .file(
            "Cargo.toml",
            r#"
                [package]
                name = "foo"
                version = "0.0.1"
                authors = []

                [features]
                quux = []
            "#,
        )
        .file("src/lib.rs", "")
        .build();

    p.cargo("rustdoc --verbose --features quux")
        .with_stderr_contains("[..]feature=[..]quux[..]")
        .run();
}

#[cargo_test]
fn proc_macro_crate_type() {
    let p = project()
        .file(
            "Cargo.toml",
            r#"
                [package]
                name = "foo"
                version = "0.0.1"
                authors = []

                [lib]
                proc-macro = true

            "#,
        )
        .file("src/lib.rs", "")
        .build();

    p.cargo("rustdoc --verbose")
        .with_stderr_contains(
            "\
[RUNNING] `rustdoc --crate-type proc-macro [..]`
",
        )
        .run();
}

#[cargo_test]
fn rustdoc_target() {
    if cross_compile::disabled() {
        return;
    }

    let p = project().file("src/lib.rs", "").build();

    p.cargo("rustdoc --verbose --target")
        .arg(cross_compile::alternate())
        .with_stderr(format!(
            "\
[DOCUMENTING] foo v0.0.1 ([..])
[RUNNING] `rustdoc [..]--crate-name foo src/lib.rs [..]\
    --target {target} \
    -o [CWD]/target/{target}/doc \
    [..] \
    -L dependency=[CWD]/target/{target}/debug/deps \
    -L dependency=[CWD]/target/debug/deps[..]`
[FINISHED] dev [unoptimized + debuginfo] target(s) in [..]",
            target = cross_compile::alternate()
        ))
        .run();
}

#[cargo_test]
fn fail_with_glob() {
    let p = project()
        .file(
            "Cargo.toml",
            r#"
            [workspace]
            members = ["bar"]
        "#,
        )
        .file("bar/Cargo.toml", &basic_manifest("bar", "0.1.0"))
        .file("bar/src/lib.rs", "pub fn bar() {  break_the_build(); }")
        .build();

    p.cargo("rustdoc -p '*z'")
        .with_status(101)
        .with_stderr("[ERROR] Glob patterns on package selection are not supported.")
        .run();
}
<|endoftext|>


<commit_before>#![warn(clippy::manual_flatten)]
#![allow(clippy::useless_vec)]

fn main() {
    // Test for loop over implicitly adjusted `Iterator` with `if let` expression
    let x = vec![Some(1), Some(2), Some(3)];
    for n in x {
        if let Some(y) = n {
            println!("{}", y);
        }
    }

    // Test for loop over implicitly implicitly adjusted `Iterator` with `if let` statement
    let y: Vec<Result<i32, i32>> = vec![];
    for n in y.clone() {
        if let Ok(n) = n {
            println!("{}", n);
        };
    }

    // Test for loop over by reference
    for n in &y {
        if let Ok(n) = n {
            println!("{}", n);
        }
    }

    // Test for loop over an implicit reference
    // Note: if `clippy::manual_flatten` is made autofixable, this case will
    // lead to a follow-up lint `clippy::into_iter_on_ref`
    let z = &y;
    for n in z {
        if let Ok(n) = n {
            println!("{}", n);
        }
    }

    // Test for loop over `Iterator` with `if let` expression
    let z = vec![Some(1), Some(2), Some(3)];
    let z = z.iter();
    for n in z {
        if let Some(m) = n {
            println!("{}", m);
        }
    }

    // Using the `None` variant should not trigger the lint
    // Note: for an autofixable suggestion, the binding in the for loop has to take the
    // name of the binding in the `if let`
    let z = vec![Some(1), Some(2), Some(3)];
    for n in z {
        if n.is_none() {
            println!("Nada.");
        }
    }

    // Using the `Err` variant should not trigger the lint
    for n in y.clone() {
        if let Err(e) = n {
            println!("Oops: {}!", e);
        }
    }

    // Having an else clause should not trigger the lint
    for n in y.clone() {
        if let Ok(n) = n {
            println!("{}", n);
        } else {
            println!("Oops!");
        }
    }

    let vec_of_ref = vec![&Some(1)];
    for n in &vec_of_ref {
        if let Some(n) = n {
            println!("{:?}", n);
        }
    }

    let vec_of_ref = &vec_of_ref;
    for n in vec_of_ref {
        if let Some(n) = n {
            println!("{:?}", n);
        }
    }

    let slice_of_ref = &[&Some(1)];
    for n in slice_of_ref {
        if let Some(n) = n {
            println!("{:?}", n);
        }
    }

    // Using manual flatten should not trigger the lint
    for n in vec![Some(1), Some(2), Some(3)].iter().flatten() {
        println!("{}", n);
    }
}
<commit_msg>Add false positive test for `manual_flatten`<commit_after>#![warn(clippy::manual_flatten)]
#![allow(clippy::useless_vec)]

fn main() {
    // Test for loop over implicitly adjusted `Iterator` with `if let` expression
    let x = vec![Some(1), Some(2), Some(3)];
    for n in x {
        if let Some(y) = n {
            println!("{}", y);
        }
    }

    // Test for loop over implicitly implicitly adjusted `Iterator` with `if let` statement
    let y: Vec<Result<i32, i32>> = vec![];
    for n in y.clone() {
        if let Ok(n) = n {
            println!("{}", n);
        };
    }

    // Test for loop over by reference
    for n in &y {
        if let Ok(n) = n {
            println!("{}", n);
        }
    }

    // Test for loop over an implicit reference
    // Note: if `clippy::manual_flatten` is made autofixable, this case will
    // lead to a follow-up lint `clippy::into_iter_on_ref`
    let z = &y;
    for n in z {
        if let Ok(n) = n {
            println!("{}", n);
        }
    }

    // Test for loop over `Iterator` with `if let` expression
    let z = vec![Some(1), Some(2), Some(3)];
    let z = z.iter();
    for n in z {
        if let Some(m) = n {
            println!("{}", m);
        }
    }

    // Using the `None` variant should not trigger the lint
    // Note: for an autofixable suggestion, the binding in the for loop has to take the
    // name of the binding in the `if let`
    let z = vec![Some(1), Some(2), Some(3)];
    for n in z {
        if n.is_none() {
            println!("Nada.");
        }
    }

    // Using the `Err` variant should not trigger the lint
    for n in y.clone() {
        if let Err(e) = n {
            println!("Oops: {}!", e);
        }
    }

    // Having an else clause should not trigger the lint
    for n in y.clone() {
        if let Ok(n) = n {
            println!("{}", n);
        } else {
            println!("Oops!");
        }
    }

    let vec_of_ref = vec![&Some(1)];
    for n in &vec_of_ref {
        if let Some(n) = n {
            println!("{:?}", n);
        }
    }

    let vec_of_ref = &vec_of_ref;
    for n in vec_of_ref {
        if let Some(n) = n {
            println!("{:?}", n);
        }
    }

    let slice_of_ref = &[&Some(1)];
    for n in slice_of_ref {
        if let Some(n) = n {
            println!("{:?}", n);
        }
    }

    struct Test {
        a: usize,
    }

    let mut vec_of_struct = [Some(Test { a: 1 }), None];

    // Usage of `if let` expression should not trigger lint
    for n in vec_of_struct.iter_mut() {
        if let Some(z) = n {
            *n = None;
        }
    }

    // Using manual flatten should not trigger the lint
    for n in vec![Some(1), Some(2), Some(3)].iter().flatten() {
        println!("{}", n);
    }
}
<|endoftext|>


<commit_before>/* kernel::sgash.rs */

use core::*;
use core::str::*;
use core::option::{Some, Option, None}; // Match statement
use core::iter::Iterator;
use core::vec::Vec;
use super::super::platform::*;

fn putchar(key: char) {
    unsafe {
	/*
	 * We need to include a blank asm call to prevent rustc
	 * from optimizing this part out
	 */
	asm!("");
	io::write_char(key, io::UART0);
    }
}

#[lang = "exchange_free"]
fn putstr(msg: &str) {
    for c in slice::iter(as_bytes(msg)) {
	putchar(*c as char);
    }
}

pub fn parsekey(x: char) {
    let x = x as u8;
    // Set this to false to learn the keycodes of various keys!
    // Key codes are printed backwards before life is hard
    if (true) {
	match x {
	    13			=>	{ prompt(); }
	    127			=>	{ putchar(''); }
				/*let a = 0x0C000008 as *u32;
				let b = *a;
				asm!("");
				if (b == 0){
				f('a');
				} else
				{
				f('b');
				}*/
				/* This isn't a real backspace */
				//f(' ');
				//f('');
				// backspace =  = 8
	    _			=>	{ putchar(x as char); }
	}
    }
    else {
	keycode(x);
    }
}

fn keycode(x: u8) {
    let mut x = x;
    while ( x != 0 ) {
	putchar((x%10+ ('0' as u8) ) as char);
	x = x/10;
    }
    putchar(' ');
}

pub unsafe fn init() {
    prompt();
}

fn prompt() {
    putstr(&"\nsgash > ");
}
<commit_msg>Comment didn't make sense<commit_after>/* kernel::sgash.rs */

use core::*;
use core::str::*;
use core::option::{Some, Option, None}; // Match statement
use core::iter::Iterator;
use core::vec::Vec;
use super::super::platform::*;

fn putchar(key: char) {
    unsafe {
	/*
	 * We need to include a blank asm call to prevent rustc
	 * from optimizing this part out
	 */
	asm!("");
	io::write_char(key, io::UART0);
    }
}

#[lang = "exchange_free"]
fn putstr(msg: &str) {
    for c in slice::iter(as_bytes(msg)) {
	putchar(*c as char);
    }
}

pub fn parsekey(x: char) {
    let x = x as u8;
    // Set this to false to learn the keycodes of various keys!
    // Key codes are printed backwards because life is hard
    if (true) {
	match x {
	    13			=>	{ prompt(); }
	    127			=>	{ putchar(''); }
				/*let a = 0x0C000008 as *u32;
				let b = *a;
				asm!("");
				if (b == 0){
				f('a');
				} else
				{
				f('b');
				}*/
				/* This isn't a real backspace */
				//f(' ');
				//f('');
				// backspace =  = 8
	    _			=>	{ putchar(x as char); }
	}
    }
    else {
	keycode(x);
    }
}

fn keycode(x: u8) {
    let mut x = x;
    while ( x != 0 ) {
	putchar((x%10+ ('0' as u8) ) as char);
	x = x/10;
    }
    putchar(' ');
}

pub unsafe fn init() {
    prompt();
}

fn prompt() {
    putstr(&"\nsgash > ");
}
<|endoftext|>


<commit_before>//! Slow down a stream by enforcing a delay between items.

use crate::stream::Stream;
use crate::time::{Delay, Duration, Instant};

use std::future::Future;
use std::marker::Unpin;
use std::pin::Pin;
use std::task::{self, Poll};

use pin_project_lite::pin_project;

/// Slows down a stream by enforcing a delay between items.
/// They will be produced not more often than the specified interval.
///
/// # Example
///
/// Create a throttled stream.
/// ```rust,norun
/// use std::time::Duration;
/// use tokio::stream::StreamExt;
/// use tokio::time::throttle;
///
/// # async fn dox() {
/// let mut item_stream = throttle(Duration::from_secs(2), futures::stream::repeat("one"));
///
/// loop {
///     // The string will be produced at most every 2 seconds
///     println!("{:?}", item_stream.next().await);
/// }
/// # }
/// ```
pub fn throttle<T>(duration: Duration, stream: T) -> Throttle<T>
where
    T: Stream,
{
    let delay = if duration == Duration::from_millis(0) {
        None
    } else {
        Some(Delay::new_timeout(Instant::now() + duration, duration))
    };

    Throttle {
        delay,
        duration,
        has_delayed: true,
        stream,
    }
}

pin_project! {
    /// Stream for the [`throttle`](throttle) function.
    #[derive(Debug)]
    #[must_use = "streams do nothing unless polled"]
    pub struct Throttle<T> {
        // `None` when duration is zero.
        delay: Option<Delay>,
        duration: Duration,

        // Set to true when `delay` has returned ready, but `stream` hasn't.
        has_delayed: bool,

        // The stream to throttle
        #[pin]
        stream: T,
    }
}

// XXX: are these safe if `T: !Unpin`?
impl<T: Unpin> Throttle<T> {
    /// Acquires a reference to the underlying stream that this combinator is
    /// pulling from.
    pub fn get_ref(&self) -> &T {
        &self.stream
    }

    /// Acquires a mutable reference to the underlying stream that this combinator
    /// is pulling from.
    ///
    /// Note that care must be taken to avoid tampering with the state of the stream
    /// which may otherwise confuse this combinator.
    pub fn get_mut(&mut self) -> &mut T {
        &mut self.stream
    }

    /// Consumes this combinator, returning the underlying stream.
    ///
    /// Note that this may discard intermediate state of this combinator, so care
    /// should be taken to avoid losing resources when this is called.
    pub fn into_inner(self) -> T {
        self.stream
    }
}

impl<T: Stream> Stream for Throttle<T> {
    type Item = T::Item;

    fn poll_next(mut self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<Option<Self::Item>> {
        if !self.has_delayed && self.delay.is_some() {
            ready!(Pin::new(self.as_mut().project().delay.as_mut().unwrap()).poll(cx));
            *self.as_mut().project().has_delayed = true;
        }

        let value = ready!(self.as_mut().project().stream.poll_next(cx));

        if value.is_some() {
            let dur = self.duration;
            if let Some(ref mut delay) = self.as_mut().project().delay {
                delay.reset(Instant::now() + dur);
            }

            *self.as_mut().project().has_delayed = false;
        }

        Poll::Ready(value)
    }
}
<commit_msg>chore: change norun to no_run (#2518)<commit_after>//! Slow down a stream by enforcing a delay between items.

use crate::stream::Stream;
use crate::time::{Delay, Duration, Instant};

use std::future::Future;
use std::marker::Unpin;
use std::pin::Pin;
use std::task::{self, Poll};

use pin_project_lite::pin_project;

/// Slows down a stream by enforcing a delay between items.
/// They will be produced not more often than the specified interval.
///
/// # Example
///
/// Create a throttled stream.
/// ```rust,no_run
/// use std::time::Duration;
/// use tokio::stream::StreamExt;
/// use tokio::time::throttle;
///
/// # async fn dox() {
/// let mut item_stream = throttle(Duration::from_secs(2), futures::stream::repeat("one"));
///
/// loop {
///     // The string will be produced at most every 2 seconds
///     println!("{:?}", item_stream.next().await);
/// }
/// # }
/// ```
pub fn throttle<T>(duration: Duration, stream: T) -> Throttle<T>
where
    T: Stream,
{
    let delay = if duration == Duration::from_millis(0) {
        None
    } else {
        Some(Delay::new_timeout(Instant::now() + duration, duration))
    };

    Throttle {
        delay,
        duration,
        has_delayed: true,
        stream,
    }
}

pin_project! {
    /// Stream for the [`throttle`](throttle) function.
    #[derive(Debug)]
    #[must_use = "streams do nothing unless polled"]
    pub struct Throttle<T> {
        // `None` when duration is zero.
        delay: Option<Delay>,
        duration: Duration,

        // Set to true when `delay` has returned ready, but `stream` hasn't.
        has_delayed: bool,

        // The stream to throttle
        #[pin]
        stream: T,
    }
}

// XXX: are these safe if `T: !Unpin`?
impl<T: Unpin> Throttle<T> {
    /// Acquires a reference to the underlying stream that this combinator is
    /// pulling from.
    pub fn get_ref(&self) -> &T {
        &self.stream
    }

    /// Acquires a mutable reference to the underlying stream that this combinator
    /// is pulling from.
    ///
    /// Note that care must be taken to avoid tampering with the state of the stream
    /// which may otherwise confuse this combinator.
    pub fn get_mut(&mut self) -> &mut T {
        &mut self.stream
    }

    /// Consumes this combinator, returning the underlying stream.
    ///
    /// Note that this may discard intermediate state of this combinator, so care
    /// should be taken to avoid losing resources when this is called.
    pub fn into_inner(self) -> T {
        self.stream
    }
}

impl<T: Stream> Stream for Throttle<T> {
    type Item = T::Item;

    fn poll_next(mut self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<Option<Self::Item>> {
        if !self.has_delayed && self.delay.is_some() {
            ready!(Pin::new(self.as_mut().project().delay.as_mut().unwrap()).poll(cx));
            *self.as_mut().project().has_delayed = true;
        }

        let value = ready!(self.as_mut().project().stream.poll_next(cx));

        if value.is_some() {
            let dur = self.duration;
            if let Some(ref mut delay) = self.as_mut().project().delay {
                delay.reset(Instant::now() + dur);
            }

            *self.as_mut().project().has_delayed = false;
        }

        Poll::Ready(value)
    }
}
<|endoftext|>


<commit_before>#![feature(async_await, await_macro, pin, arbitrary_self_types, futures_api)]

use futures::{Poll, future, pending, poll, pin_mut, join, try_join, select};
use futures::channel::oneshot;
use futures::executor::block_on;

#[test]
fn poll_and_pending() {
    let pending_once = async { pending!() };
    block_on(async {
        pin_mut!(pending_once);
        assert_eq!(Poll::Pending, poll!(&mut pending_once));
        assert_eq!(Poll::Ready(()), poll!(&mut pending_once));
    });
}

#[test]
fn join() {
    let (tx1, rx1) = oneshot::channel::<i32>();
    let (tx2, rx2) = oneshot::channel::<i32>();

    let fut = async {
        let res = join!(rx1, rx2);
        assert_eq!((Ok(1), Ok(2)), res);
    };

    block_on(async {
        pin_mut!(fut);
        assert_eq!(Poll::Pending, poll!(&mut fut));
        tx1.send(1).unwrap();
        assert_eq!(Poll::Pending, poll!(&mut fut));
        tx2.send(2).unwrap();
        assert_eq!(Poll::Ready(()), poll!(&mut fut));
    });
}

#[test]
fn select() {
    let (tx1, mut rx1) = oneshot::channel::<i32>();
    let (_tx2, mut rx2) = oneshot::channel::<i32>();
    tx1.send(1).unwrap();
    let mut ran = false;
    block_on(async {
        select! {
            rx1 => {
                assert_eq!(Ok(1), rx1);
                ran = true;
            },
            rx2 => unreachable!(),
        }
    });
    assert!(ran);
}

#[test]
fn select_can_move_uncompleted_futures() {
    let (tx1, mut rx1) = oneshot::channel::<i32>();
    let (tx2, mut rx2) = oneshot::channel::<i32>();
    tx1.send(1).unwrap();
    tx2.send(2).unwrap();
    let mut ran = false;
    block_on(async {
        select! {
            rx1 => {
                assert_eq!(Ok(1), rx1);
                assert_eq!(Ok(2), await!(rx2));
                ran = true;
            },
            rx2 => {
                assert_eq!(Ok(2), rx2);
                assert_eq!(Ok(1), await!(rx1));
                ran = true;
            },
        }
    });
    assert!(ran);
}

#[test]
fn select_size() {
    let fut = async {
        let mut ready = future::ready(0i32);
        select! {
            ready => {},
        }
    };
    assert_eq!(::std::mem::size_of_val(&fut), 40);

    let fut = async {
        let mut ready1 = future::ready(0i32);
        let mut ready2 = future::ready(0i32);
        select! {
            ready1 => {},
            ready2 => {},
        }
    };
    assert_eq!(::std::mem::size_of_val(&fut), 56);
}

#[test]
fn join_size() {
    let fut = async {
        let ready = future::ready(0i32);
        join!(ready)
    };
    assert_eq!(::std::mem::size_of_val(&fut), 32);

    let fut = async {
        let ready1 = future::ready(0i32);
        let ready2 = future::ready(0i32);
        join!(ready1, ready2)
    };
    assert_eq!(::std::mem::size_of_val(&fut), 64);
}

#[test]
fn try_join_size() {
    let fut = async {
        let ready = future::ready(Ok::<i32, i32>(0));
        try_join!(ready)
    };
    assert_eq!(::std::mem::size_of_val(&fut), 32);

    let fut = async {
        let ready1 = future::ready(Ok::<i32, i32>(0));
        let ready2 = future::ready(Ok::<i32, i32>(0));
        try_join!(ready1, ready2)
    };
    assert_eq!(::std::mem::size_of_val(&fut), 64);
}

#[test]
fn join_doesnt_require_unpin() {
    let _ = async {
        let x = async {};
        let y = async {};
        join!(x, y)
    };
}

#[test]
fn try_join_doesnt_require_unpin() {
    let _ = async {
        let x = async { Ok::<(), ()>(()) };
        let y = async { Ok::<(), ()>(()) };
        try_join!(x, y)
    };
}
<commit_msg>Update size assertions<commit_after>#![feature(async_await, await_macro, pin, arbitrary_self_types, futures_api)]

use futures::{Poll, future, pending, poll, pin_mut, join, try_join, select};
use futures::channel::oneshot;
use futures::executor::block_on;

#[test]
fn poll_and_pending() {
    let pending_once = async { pending!() };
    block_on(async {
        pin_mut!(pending_once);
        assert_eq!(Poll::Pending, poll!(&mut pending_once));
        assert_eq!(Poll::Ready(()), poll!(&mut pending_once));
    });
}

#[test]
fn join() {
    let (tx1, rx1) = oneshot::channel::<i32>();
    let (tx2, rx2) = oneshot::channel::<i32>();

    let fut = async {
        let res = join!(rx1, rx2);
        assert_eq!((Ok(1), Ok(2)), res);
    };

    block_on(async {
        pin_mut!(fut);
        assert_eq!(Poll::Pending, poll!(&mut fut));
        tx1.send(1).unwrap();
        assert_eq!(Poll::Pending, poll!(&mut fut));
        tx2.send(2).unwrap();
        assert_eq!(Poll::Ready(()), poll!(&mut fut));
    });
}

#[test]
fn select() {
    let (tx1, mut rx1) = oneshot::channel::<i32>();
    let (_tx2, mut rx2) = oneshot::channel::<i32>();
    tx1.send(1).unwrap();
    let mut ran = false;
    block_on(async {
        select! {
            rx1 => {
                assert_eq!(Ok(1), rx1);
                ran = true;
            },
            rx2 => unreachable!(),
        }
    });
    assert!(ran);
}

#[test]
fn select_can_move_uncompleted_futures() {
    let (tx1, mut rx1) = oneshot::channel::<i32>();
    let (tx2, mut rx2) = oneshot::channel::<i32>();
    tx1.send(1).unwrap();
    tx2.send(2).unwrap();
    let mut ran = false;
    block_on(async {
        select! {
            rx1 => {
                assert_eq!(Ok(1), rx1);
                assert_eq!(Ok(2), await!(rx2));
                ran = true;
            },
            rx2 => {
                assert_eq!(Ok(2), rx2);
                assert_eq!(Ok(1), await!(rx1));
                ran = true;
            },
        }
    });
    assert!(ran);
}

#[test]
fn select_size() {
    let fut = async {
        let mut ready = future::ready(0i32);
        select! {
            ready => {},
        }
    };
    assert_eq!(::std::mem::size_of_val(&fut), 24);

    let fut = async {
        let mut ready1 = future::ready(0i32);
        let mut ready2 = future::ready(0i32);
        select! {
            ready1 => {},
            ready2 => {},
        }
    };
    assert_eq!(::std::mem::size_of_val(&fut), 40);
}

#[test]
fn join_size() {
    let fut = async {
        let ready = future::ready(0i32);
        join!(ready)
    };
    assert_eq!(::std::mem::size_of_val(&fut), 16);

    let fut = async {
        let ready1 = future::ready(0i32);
        let ready2 = future::ready(0i32);
        join!(ready1, ready2)
    };
    assert_eq!(::std::mem::size_of_val(&fut), 44);
}

#[test]
fn try_join_size() {
    let fut = async {
        let ready = future::ready(Ok::<i32, i32>(0));
        try_join!(ready)
    };
    assert_eq!(::std::mem::size_of_val(&fut), 16);

    let fut = async {
        let ready1 = future::ready(Ok::<i32, i32>(0));
        let ready2 = future::ready(Ok::<i32, i32>(0));
        try_join!(ready1, ready2)
    };
    assert_eq!(::std::mem::size_of_val(&fut), 44);
}

#[test]
fn join_doesnt_require_unpin() {
    let _ = async {
        let x = async {};
        let y = async {};
        join!(x, y)
    };
}

#[test]
fn try_join_doesnt_require_unpin() {
    let _ = async {
        let x = async { Ok::<(), ()>(()) };
        let y = async { Ok::<(), ()>(()) };
        try_join!(x, y)
    };
}
<|endoftext|>


<commit_before>// Copyright 2015-2017 Intecture Developers.
//
// Licensed under the Mozilla Public License 2.0 <LICENSE or
// https://www.tldrlegal.com/l/mpl-2.0>. This file may not be copied,
// modified, or distributed except according to those terms.

extern crate futures;
extern crate intecture_api;
extern crate tokio_core;

use futures::Future;
use intecture_api::prelude::*;
use tokio_core::reactor::Core;

fn main() {
    let mut core = Core::new().unwrap();

    let host = Local::new().and_then(|host| {
        command::factory(&host, "whoami", None).and_then(|mut cmd| {
            cmd.exec().map(|out| {
                println!("I'm currently running as {}", String::from_utf8_lossy(&out.stdout).trim());
            })
        })
    });

    core.run(host).unwrap();
}
<commit_msg>Fix core examples<commit_after>// Copyright 2015-2017 Intecture Developers.
//
// Licensed under the Mozilla Public License 2.0 <LICENSE or
// https://www.tldrlegal.com/l/mpl-2.0>. This file may not be copied,
// modified, or distributed except according to those terms.

extern crate futures;
extern crate intecture_api;
extern crate tokio_core;

use futures::Future;
use intecture_api::prelude::*;
use tokio_core::reactor::Core;

fn main() {
    let mut core = Core::new().unwrap();

    let host = Local::new().and_then(|host| {
        Command::new(&host, "whoami", None).and_then(|mut cmd| {
            cmd.exec().map(|out| {
                println!("I'm currently running as {}", String::from_utf8_lossy(&out.stdout).trim());
            })
        })
    });

    core.run(host).unwrap();
}
<|endoftext|>


<commit_before>use super::*;

macro_rules! ehi {
    ($x:ty, $ctr:ident, $e:ident, $c:block) => {
        impl<'a> EventsHandler for $x {
            fn event(&mut self, $e : Event) {*self.$ctr += 1; $c }
            fn log(&mut self, m : &str) { println!("{}", m); }
        }
    }

}

#[test]
fn element_parse_test_1() {
    let mut ctr = 0;
    struct Q<'a> { ctr: &'a mut i32};
    ehi!(Q<'a>, ctr, e, {
        match e {
            Event::Resync => (),
            _ => panic!("Expected resync"),
        }
    });
    {
        let mut p = super::new(Q{ctr : &mut ctr});
        p.feed_bytes(&[255, 255, 255, 255]);
    }
    assert_eq!(ctr, 1);
}
<commit_msg>Tests for parser based on debug_logger<commit_after>use super::*;
use super::debug::*;
use std::io::Write;
use std::str::from_utf8;

macro_rules! t {
    ($input:expr, $output:expr) => {{{
        let mut out = vec!();
        {
            let mut p = super::new( debug_logger(&mut out as &mut Write)  );
            p.feed_bytes(&$input);
        }
        assert_eq!(from_utf8(out.as_slice()), Ok($output));
    }{
        let mut out = vec!();
        {
            let mut p = super::new( debug_logger(&mut out as &mut Write)  );
            for i in $input.iter() {
                p.feed_bytes(&[*i]);
            }
        }
        assert_eq!(from_utf8(out.as_slice()), Ok($output));
    }}}
}

#[test] fn t1() {
t!( [0xA3, 0x82, 33, 44] ,
r#"element SimpleBlock(offset:0, rawlen:4)
 data Binary([33, 44])
end SimpleBlock(offset:0, rawlen:4)
"#);}

#[test] fn t2() {
t!( [255, 255, 255, 255],
r#"resync
"#);}

#[test] fn t3() {
t!( [
  0x1a, 0x45, 0xdf, 0xa3, 0xa3, 0x42, 0x86, 0x81, 0x01, 0x42, 0xf7, 0x81,
  0x01, 0x42, 0xf2, 0x81, 0x04, 0x42, 0xf3, 0x81, 0x08, 0x42, 0x82, 0x88,
  0x6d, 0x61, 0x74, 0x72, 0x6f, 0x73, 0x6b, 0x61, 0x42, 0x87, 0x81, 0x02,
  0x42, 0x85, 0x81, 0x02
],
r#"element EBML(offset:0, rawlen:40)
 element EBMLVersion(offset:5, rawlen:4)
  data Unsigned(1)
 end EBMLVersion(offset:5, rawlen:4)
 element EBMLReadVersion(offset:9, rawlen:4)
  data Unsigned(1)
 end EBMLReadVersion(offset:9, rawlen:4)
 element EBMLMaxIDLength(offset:13, rawlen:4)
  data Unsigned(4)
 end EBMLMaxIDLength(offset:13, rawlen:4)
 element EBMLMaxSizeLength(offset:17, rawlen:4)
  data Unsigned(8)
 end EBMLMaxSizeLength(offset:17, rawlen:4)
 element DocType(offset:21, rawlen:11)
  data Text("matroska")
 end DocType(offset:21, rawlen:11)
 element DocTypeVersion(offset:32, rawlen:4)
  data Unsigned(2)
 end DocTypeVersion(offset:32, rawlen:4)
 element DocTypeReadVersion(offset:36, rawlen:4)
  data Unsigned(2)
 end DocTypeReadVersion(offset:36, rawlen:4)
end EBML(offset:0, rawlen:40)
"#);}

#[test] fn t4() {
t!( [ 0xff, 0xff, 0x1a, 0x45, 0xdf, 0xa3, 0xa3],
r#"resync
element EBML(offset:2, rawlen:40)
"#);}

#[test] fn t5() {
t!( [ 0x44, 0x89, 0x84, 0x42, 0xe8, 0x00, 0x00 ],
r#"element Duration(offset:0, rawlen:7)
 data Float(116)
end Duration(offset:0, rawlen:7)
"#);}

#[test] fn t6() {
t!( [ 0x86, 0x85, 0x41, 0x42, 0x43, 0x44, 0x45 ],
r#"element CodecID(offset:0, rawlen:7)
 data Text("ABCDE")
end CodecID(offset:0, rawlen:7)
"#);}
<|endoftext|>


<commit_before>use std::collections::HashMap;

use crossfont::Metrics;

use alacritty_terminal::index::{Line, Point};
use alacritty_terminal::term::cell::Flags;
use alacritty_terminal::term::color::Rgb;
use alacritty_terminal::term::{RenderableCell, SizeInfo};

#[derive(Debug, Copy, Clone)]
pub struct RenderRect {
    pub x: f32,
    pub y: f32,
    pub width: f32,
    pub height: f32,
    pub color: Rgb,
    pub alpha: f32,
}

impl RenderRect {
    pub fn new(x: f32, y: f32, width: f32, height: f32, color: Rgb, alpha: f32) -> Self {
        RenderRect { x, y, width, height, color, alpha }
    }
}

#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct RenderLine {
    pub start: Point,
    pub end: Point,
    pub color: Rgb,
}

impl RenderLine {
    pub fn rects(&self, flag: Flags, metrics: &Metrics, size: &SizeInfo) -> Vec<RenderRect> {
        let mut rects = Vec::new();

        let mut start = self.start;
        for line in start.line.0..=self.end.line.0 {
            let mut end = Point::new(Line(line), self.end.col);
            if line != self.end.line.0 {
                end.col = size.cols() - 1;
            }

            Self::push_rects(&mut rects, metrics, size, flag, start, end, self.color);

            start.col.0 = 0;
        }

        rects
    }

    /// Push all rects required to draw the cell's line.
    fn push_rects(
        rects: &mut Vec<RenderRect>,
        metrics: &Metrics,
        size: &SizeInfo,
        flag: Flags,
        start: Point,
        end: Point,
        color: Rgb,
    ) {
        let (position, thickness) = match flag {
            Flags::DOUBLE_UNDERLINE => {
                // Position underlines so each one has 50% of descent available.
                let top_pos = 0.25 * metrics.descent;
                let bottom_pos = 0.75 * metrics.descent;

                rects.push(Self::create_rect(
                    size,
                    metrics.descent,
                    start,
                    end,
                    top_pos,
                    metrics.underline_thickness,
                    color,
                ));

                (bottom_pos, metrics.underline_thickness)
            },
            Flags::UNDERLINE => (metrics.underline_position, metrics.underline_thickness),
            Flags::STRIKEOUT => (metrics.strikeout_position, metrics.strikeout_thickness),
            _ => unimplemented!("Invalid flag for cell line drawing specified"),
        };

        rects.push(Self::create_rect(
            size,
            metrics.descent,
            start,
            end,
            position,
            thickness,
            color,
        ));
    }

    /// Create a line's rect at a position relative to the baseline.
    fn create_rect(
        size: &SizeInfo,
        descent: f32,
        start: Point,
        end: Point,
        position: f32,
        mut thickness: f32,
        color: Rgb,
    ) -> RenderRect {
        let start_x = start.col.0 as f32 * size.cell_width;
        let end_x = (end.col.0 + 1) as f32 * size.cell_width;
        let width = end_x - start_x;

        // Make sure lines are always visible.
        thickness = thickness.max(1.);

        let line_bottom = (start.line.0 as f32 + 1.) * size.cell_height;
        let baseline = line_bottom + descent;

        let mut y = (baseline - position - thickness / 2.).ceil();
        let max_y = line_bottom - thickness;
        if y > max_y {
            y = max_y;
        }

        RenderRect::new(start_x + size.padding_x, y + size.padding_y, width, thickness, color, 1.)
    }
}

/// Lines for underline and strikeout.
#[derive(Default)]
pub struct RenderLines {
    inner: HashMap<Flags, Vec<RenderLine>>,
}

impl RenderLines {
    #[inline]
    pub fn new() -> Self {
        Self::default()
    }

    #[inline]
    pub fn rects(&self, metrics: &Metrics, size: &SizeInfo) -> Vec<RenderRect> {
        self.inner
            .iter()
            .map(|(flag, lines)| -> Vec<RenderRect> {
                lines.iter().map(|line| line.rects(*flag, metrics, size)).flatten().collect()
            })
            .flatten()
            .collect()
    }

    /// Update the stored lines with the next cell info.
    #[inline]
    pub fn update(&mut self, cell: RenderableCell) {
        self.update_flag(cell, Flags::UNDERLINE);
        self.update_flag(cell, Flags::DOUBLE_UNDERLINE);
        self.update_flag(cell, Flags::STRIKEOUT);
    }

    /// Update the lines for a specific flag.
    fn update_flag(&mut self, cell: RenderableCell, flag: Flags) {
        if !cell.flags.contains(flag) {
            return;
        }

        // Check if there's an active line.
        if let Some(line) = self.inner.get_mut(&flag).and_then(|lines| lines.last_mut()) {
            if cell.fg == line.color
                && cell.column == line.end.col + 1
                && cell.line == line.end.line
            {
                // Update the length of the line.
                line.end = cell.into();
                return;
            }
        }

        // Start new line if there currently is none.
        let line = RenderLine { start: cell.into(), end: cell.into(), color: cell.fg };
        match self.inner.get_mut(&flag) {
            Some(lines) => lines.push(line),
            None => {
                self.inner.insert(flag, vec![line]);
            },
        }
    }
}
<commit_msg>Fix multiline URL highlighting<commit_after>use std::collections::HashMap;

use crossfont::Metrics;

use alacritty_terminal::index::{Column, Point};
use alacritty_terminal::term::cell::Flags;
use alacritty_terminal::term::color::Rgb;
use alacritty_terminal::term::{RenderableCell, SizeInfo};

#[derive(Debug, Copy, Clone)]
pub struct RenderRect {
    pub x: f32,
    pub y: f32,
    pub width: f32,
    pub height: f32,
    pub color: Rgb,
    pub alpha: f32,
}

impl RenderRect {
    pub fn new(x: f32, y: f32, width: f32, height: f32, color: Rgb, alpha: f32) -> Self {
        RenderRect { x, y, width, height, color, alpha }
    }
}

#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct RenderLine {
    pub start: Point,
    pub end: Point,
    pub color: Rgb,
}

impl RenderLine {
    pub fn rects(&self, flag: Flags, metrics: &Metrics, size: &SizeInfo) -> Vec<RenderRect> {
        let mut rects = Vec::new();

        let mut start = self.start;
        while start.line < self.end.line {
            let end = Point::new(start.line, size.cols() - 1);
            Self::push_rects(&mut rects, metrics, size, flag, start, end, self.color);
            start = Point::new(start.line + 1, Column(0));
        }
        Self::push_rects(&mut rects, metrics, size, flag, start, self.end, self.color);

        rects
    }

    /// Push all rects required to draw the cell's line.
    fn push_rects(
        rects: &mut Vec<RenderRect>,
        metrics: &Metrics,
        size: &SizeInfo,
        flag: Flags,
        start: Point,
        end: Point,
        color: Rgb,
    ) {
        let (position, thickness) = match flag {
            Flags::DOUBLE_UNDERLINE => {
                // Position underlines so each one has 50% of descent available.
                let top_pos = 0.25 * metrics.descent;
                let bottom_pos = 0.75 * metrics.descent;

                rects.push(Self::create_rect(
                    size,
                    metrics.descent,
                    start,
                    end,
                    top_pos,
                    metrics.underline_thickness,
                    color,
                ));

                (bottom_pos, metrics.underline_thickness)
            },
            Flags::UNDERLINE => (metrics.underline_position, metrics.underline_thickness),
            Flags::STRIKEOUT => (metrics.strikeout_position, metrics.strikeout_thickness),
            _ => unimplemented!("Invalid flag for cell line drawing specified"),
        };

        rects.push(Self::create_rect(
            size,
            metrics.descent,
            start,
            end,
            position,
            thickness,
            color,
        ));
    }

    /// Create a line's rect at a position relative to the baseline.
    fn create_rect(
        size: &SizeInfo,
        descent: f32,
        start: Point,
        end: Point,
        position: f32,
        mut thickness: f32,
        color: Rgb,
    ) -> RenderRect {
        let start_x = start.col.0 as f32 * size.cell_width;
        let end_x = (end.col.0 + 1) as f32 * size.cell_width;
        let width = end_x - start_x;

        // Make sure lines are always visible.
        thickness = thickness.max(1.);

        let line_bottom = (start.line.0 as f32 + 1.) * size.cell_height;
        let baseline = line_bottom + descent;

        let mut y = (baseline - position - thickness / 2.).ceil();
        let max_y = line_bottom - thickness;
        if y > max_y {
            y = max_y;
        }

        RenderRect::new(start_x + size.padding_x, y + size.padding_y, width, thickness, color, 1.)
    }
}

/// Lines for underline and strikeout.
#[derive(Default)]
pub struct RenderLines {
    inner: HashMap<Flags, Vec<RenderLine>>,
}

impl RenderLines {
    #[inline]
    pub fn new() -> Self {
        Self::default()
    }

    #[inline]
    pub fn rects(&self, metrics: &Metrics, size: &SizeInfo) -> Vec<RenderRect> {
        self.inner
            .iter()
            .map(|(flag, lines)| -> Vec<RenderRect> {
                lines.iter().map(|line| line.rects(*flag, metrics, size)).flatten().collect()
            })
            .flatten()
            .collect()
    }

    /// Update the stored lines with the next cell info.
    #[inline]
    pub fn update(&mut self, cell: RenderableCell) {
        self.update_flag(cell, Flags::UNDERLINE);
        self.update_flag(cell, Flags::DOUBLE_UNDERLINE);
        self.update_flag(cell, Flags::STRIKEOUT);
    }

    /// Update the lines for a specific flag.
    fn update_flag(&mut self, cell: RenderableCell, flag: Flags) {
        if !cell.flags.contains(flag) {
            return;
        }

        // Check if there's an active line.
        if let Some(line) = self.inner.get_mut(&flag).and_then(|lines| lines.last_mut()) {
            if cell.fg == line.color
                && cell.column == line.end.col + 1
                && cell.line == line.end.line
            {
                // Update the length of the line.
                line.end = cell.into();
                return;
            }
        }

        // Start new line if there currently is none.
        let line = RenderLine { start: cell.into(), end: cell.into(), color: cell.fg };
        match self.inner.get_mut(&flag) {
            Some(lines) => lines.push(line),
            None => {
                self.inner.insert(flag, vec![line]);
            },
        }
    }
}
<|endoftext|>