<commit_before>use std::str::Chars;
use std::iter::Peekable;
use std::iter::Enumerate;

use ::syntax::lexer::{Token, Lexer, Span};
use ::syntax::next_is;

pub struct RustSyntax;

impl Lexer for RustSyntax {
    fn handle_char(&self, ch: char, mut iter: &mut Peekable<Enumerate<Chars>>, y_pos: usize, idx: usize) -> Option<Span> {
        match ch {
            '#' => {
                let st = idx;
                let mut end = idx;
                if next_is(&mut iter, '!') || next_is(&mut iter, '[') {
                    let mut s = String::from("#");
                    while let Some(&(e, c)) = iter.peek() {
                        if c == '\n' { break }
                        end = e;
                        s.push(iter.next().unwrap().1)
                    }
                    return Some(Span {
                        y_pos: y_pos,
                        start: st,
                        end: end,
                        token: Token::Attribute(s),
                    });
                }
                return Some(Span{y_pos: y_pos, start: idx, end: idx + 1, token: Token::Hash})
            }

            '/' => {
                let st = idx;
                let mut end = idx;
                if next_is(&mut iter, '/') {
                    let mut s = String::from("/");
                    s.push(iter.next().unwrap().1);

                    let mut doc_comment = false;
                    if next_is(&mut iter, '/') {
                        doc_comment = true;
                    }

                    while let Some(&(e, c)) = iter.peek() {
                        if c == '\n' { break }
                        end = e;
                        s.push(iter.next().unwrap().1)
                    }

                    return Some(Span {
                        y_pos: y_pos,
                        start: st,
                        end: end,
                        token: if doc_comment{ Token::DocComment(s) } else { Token::SingleLineComment(s) },
                    });
                }
                return Some(Span {
                    y_pos: y_pos,
                    start: st,
                    end: end,
                    token: Token::ForwardSlash,
                });
            }

            '"' => {
                let st = idx;
                let mut end = idx;
                let mut s = String::from("\"");
                while let Some(&(e, c)) = iter.peek() {
                    end = e;
                    s.push(iter.next().unwrap().1);
                    if c == '\\' {
                        if let Some(&(e, c_)) = iter.peek() {
                            // this is handling escaped single quotes...
                            if c_ == '"' {
                                s.push(iter.next().unwrap().1);
                                continue;
                            }
                        }
                    }
                    if c == '"' {
                        break;
                    }
                }
                return Some(Span {
                    y_pos: y_pos,
                    start: st,
                    end: end,
                    token: Token::String(s),
                });
            }

            // TODO: this was horribly broken - figure out how to fix it
            // FIXME:
            // '\'' => {
            //     let st = idx;
            //     let mut end = idx;
            //     let mut s = String::from("\'");
            //     while let Some(&(e, c)) = iter.peek() {
            //         end = e;
            //         s.push(iter.next().unwrap().1);
            //         if c == '\\' {
            //             if let Some(&(e, c_)) = iter.peek() {
            //                 // this is handling escaped single quotes...
            //                 if c_ == '\'' {
            //                     s.push(iter.next().unwrap().1);
            //                     continue;
            //                 }
            //             }
            //         }
            //         if c == '\'' {
            //             break;
            //         }
            //     }
            //     return Some(Span {
            //         y_pos: y_pos,
            //         start: st,
            //         end: end,
            //         token: Token::Special(s),
            //     });
            // }

            _ => None,
        }

    }

    fn handle_ident(&self, ch: char, mut iter: &mut Peekable<Enumerate<Chars>>, y_pos: usize) -> Span {
        let mut ident = String::new();
        ident.push(ch);
        let mut start = 0;

        if let Some(&(x, c)) = iter.peek() {
            start = x - 1;
        }

        while self.is_ident(iter.peek()) {
            ident.push(iter.next().unwrap().1)
        }

        let end = ident.len() - 1;
        let token;

        if next_is(&mut iter, '(') {
            token = Token::FunctionCallDef(ident);
        } else {
            token = Token::Ident(ident);
        }

        Span {
            y_pos: y_pos,
            start: start,
            end: start + end,
            token: token,
        }
    }
}

<commit_msg>Highlight crate level doc comments in rust<commit_after>use std::str::Chars;
use std::iter::Peekable;
use std::iter::Enumerate;

use ::syntax::lexer::{Token, Lexer, Span};
use ::syntax::next_is;

pub struct RustSyntax;

impl Lexer for RustSyntax {
    fn handle_char(&self, ch: char, mut iter: &mut Peekable<Enumerate<Chars>>, y_pos: usize, idx: usize) -> Option<Span> {
        match ch {
            '#' => {
                let st = idx;
                let mut end = idx;
                if next_is(&mut iter, '!') || next_is(&mut iter, '[') {
                    let mut s = String::from("#");
                    while let Some(&(e, c)) = iter.peek() {
                        if c == '\n' { break }
                        end = e;
                        s.push(iter.next().unwrap().1)
                    }
                    return Some(Span {
                        y_pos: y_pos,
                        start: st,
                        end: end,
                        token: Token::Attribute(s),
                    });
                }
                return Some(Span{y_pos: y_pos, start: idx, end: idx + 1, token: Token::Hash})
            }

            '/' => {
                let st = idx;
                let mut end = idx;
                if next_is(&mut iter, '/') {
                    let mut s = String::from("/");
                    s.push(iter.next().unwrap().1);

                    let mut doc_comment = false;
                    if next_is(&mut iter, '/') || next_is(&mut iter, '!') {
                        doc_comment = true;
                    }

                    while let Some(&(e, c)) = iter.peek() {
                        if c == '\n' { break }
                        end = e;
                        s.push(iter.next().unwrap().1)
                    }

                    return Some(Span {
                        y_pos: y_pos,
                        start: st,
                        end: end,
                        token: if doc_comment{ Token::DocComment(s) } else { Token::SingleLineComment(s) },
                    });
                }
                return Some(Span {
                    y_pos: y_pos,
                    start: st,
                    end: end,
                    token: Token::ForwardSlash,
                });
            }

            '"' => {
                let st = idx;
                let mut end = idx;
                let mut s = String::from("\"");
                while let Some(&(e, c)) = iter.peek() {
                    end = e;
                    s.push(iter.next().unwrap().1);
                    if c == '\\' {
                        if let Some(&(e, c_)) = iter.peek() {
                            // this is handling escaped single quotes...
                            if c_ == '"' {
                                s.push(iter.next().unwrap().1);
                                continue;
                            }
                        }
                    }
                    if c == '"' {
                        break;
                    }
                }
                return Some(Span {
                    y_pos: y_pos,
                    start: st,
                    end: end,
                    token: Token::String(s),
                });
            }

            // TODO: this was horribly broken - figure out how to fix it
            // FIXME:
            // '\'' => {
            //     let st = idx;
            //     let mut end = idx;
            //     let mut s = String::from("\'");
            //     while let Some(&(e, c)) = iter.peek() {
            //         end = e;
            //         s.push(iter.next().unwrap().1);
            //         if c == '\\' {
            //             if let Some(&(e, c_)) = iter.peek() {
            //                 // this is handling escaped single quotes...
            //                 if c_ == '\'' {
            //                     s.push(iter.next().unwrap().1);
            //                     continue;
            //                 }
            //             }
            //         }
            //         if c == '\'' {
            //             break;
            //         }
            //     }
            //     return Some(Span {
            //         y_pos: y_pos,
            //         start: st,
            //         end: end,
            //         token: Token::Special(s),
            //     });
            // }

            _ => None,
        }

    }

    fn handle_ident(&self, ch: char, mut iter: &mut Peekable<Enumerate<Chars>>, y_pos: usize) -> Span {
        let mut ident = String::new();
        ident.push(ch);
        let mut start = 0;

        if let Some(&(x, c)) = iter.peek() {
            start = x - 1;
        }

        while self.is_ident(iter.peek()) {
            ident.push(iter.next().unwrap().1)
        }

        let end = ident.len() - 1;
        let token;

        if next_is(&mut iter, '(') {
            token = Token::FunctionCallDef(ident);
        } else {
            token = Token::Ident(ident);
        }

        Span {
            y_pos: y_pos,
            start: start,
            end: start + end,
            token: token,
        }
    }
}

<|endoftext|>


<commit_before>// Copyright (c) The Libra Core Contributors
// SPDX-License-Identifier: Apache-2.0

use crate::storage::{BackupStorage, ShellSafeName, TextLine};
use anyhow::Result;
use itertools::Itertools;
use libra_temppath::TempPath;
use proptest::{
    collection::{hash_map, vec},
    prelude::*,
};
use std::collections::HashMap;
use tokio::{
    io::{AsyncReadExt, AsyncWriteExt},
    time::{delay_for, Duration},
};

fn to_file_name(tmpdir: &TempPath, backup_name: &str, file_name: &str) -> String {
    tmpdir
        .path()
        .to_path_buf()
        .join(backup_name)
        .join(file_name)
        .into_os_string()
        .into_string()
        .unwrap()
}

pub async fn test_write_and_read_impl(
    store: Box<dyn BackupStorage>,
    tmpdir: &TempPath,
    backups: HashMap<ShellSafeName, HashMap<ShellSafeName, Vec<u8>>>,
) {
    for (backup_name, files) in &backups {
        let backup_handle = store.create_backup(backup_name).await.unwrap();
        assert_eq!(backup_handle, backup_name.as_ref());
        for (name, content) in files {
            let (handle, mut file) = store.create_for_write(&backup_handle, name).await.unwrap();
            assert_eq!(handle, to_file_name(&tmpdir, backup_name, name));
            file.write_all(content).await.unwrap();
        }
    }

    for (backup_name, files) in &backups {
        for (name, content) in files {
            let handle = to_file_name(&tmpdir, backup_name, name);
            let mut file = store.open_for_read(&handle).await.unwrap();
            let mut buf = Vec::new();
            file.read_to_end(&mut buf).await.unwrap();
            assert_eq!(content, &buf);
        }
    }
}

pub fn arb_backups(
) -> impl Strategy<Value = HashMap<ShellSafeName, HashMap<ShellSafeName, Vec<u8>>>> {
    hash_map(
        any::<ShellSafeName>(), // backup_name
        hash_map(
            any::<ShellSafeName>(),    // file name
            vec(any::<u8>(), 1..1000), // file content
            1..10,
        ),
        1..10,
    )
}

pub async fn test_save_and_list_metadata_files_impl(
    store: Box<dyn BackupStorage>,
    input: Vec<(ShellSafeName, TextLine)>,
) {
    for (name, content) in &input {
        store.save_metadata_line(name, &content).await.unwrap();
    }

    // It takes a little time for the ls command to reflect newly created entries
    // it's not a problem in real world.
    delay_for(Duration::from_millis(50)).await;

    let mut read_back = Vec::new();
    for file_handle in store.list_metadata_files().await.unwrap() {
        let mut buf = String::new();
        store
            .open_for_read(&file_handle)
            .await
            .unwrap()
            .read_to_string(&mut buf)
            .await
            .unwrap();
        read_back.extend(
            buf.lines()
                .map(TextLine::new)
                .collect::<Result<Vec<_>>>()
                .unwrap()
                .into_iter(),
        )
    }
    read_back.sort();

    let expected = input
        .into_iter()
        .map(|(_name, content)| content)
        .sorted()
        .collect::<Vec<_>>();

    assert_eq!(read_back, expected)
}

pub fn arb_metadata_files() -> impl Strategy<Value = Vec<(ShellSafeName, TextLine)>> {
    vec(any::<(ShellSafeName, TextLine)>(), 0..10)
}
<commit_msg>[backup] in test: call `sync` instead of wait for 50ms<commit_after>// Copyright (c) The Libra Core Contributors
// SPDX-License-Identifier: Apache-2.0

use crate::storage::{BackupStorage, ShellSafeName, TextLine};
use anyhow::Result;
use itertools::Itertools;
use libra_temppath::TempPath;
use proptest::{
    collection::{hash_map, vec},
    prelude::*,
};
use std::{collections::HashMap, process::Stdio};
use tokio::io::{AsyncReadExt, AsyncWriteExt};

fn to_file_name(tmpdir: &TempPath, backup_name: &str, file_name: &str) -> String {
    tmpdir
        .path()
        .to_path_buf()
        .join(backup_name)
        .join(file_name)
        .into_os_string()
        .into_string()
        .unwrap()
}

pub async fn test_write_and_read_impl(
    store: Box<dyn BackupStorage>,
    tmpdir: &TempPath,
    backups: HashMap<ShellSafeName, HashMap<ShellSafeName, Vec<u8>>>,
) {
    for (backup_name, files) in &backups {
        let backup_handle = store.create_backup(backup_name).await.unwrap();
        assert_eq!(backup_handle, backup_name.as_ref());
        for (name, content) in files {
            let (handle, mut file) = store.create_for_write(&backup_handle, name).await.unwrap();
            assert_eq!(handle, to_file_name(&tmpdir, backup_name, name));
            file.write_all(content).await.unwrap();
        }
    }

    for (backup_name, files) in &backups {
        for (name, content) in files {
            let handle = to_file_name(&tmpdir, backup_name, name);
            let mut file = store.open_for_read(&handle).await.unwrap();
            let mut buf = Vec::new();
            file.read_to_end(&mut buf).await.unwrap();
            assert_eq!(content, &buf);
        }
    }
}

pub fn arb_backups(
) -> impl Strategy<Value = HashMap<ShellSafeName, HashMap<ShellSafeName, Vec<u8>>>> {
    hash_map(
        any::<ShellSafeName>(), // backup_name
        hash_map(
            any::<ShellSafeName>(),    // file name
            vec(any::<u8>(), 1..1000), // file content
            1..10,
        ),
        1..10,
    )
}

pub async fn test_save_and_list_metadata_files_impl(
    store: Box<dyn BackupStorage>,
    input: Vec<(ShellSafeName, TextLine)>,
) {
    for (name, content) in &input {
        store.save_metadata_line(name, &content).await.unwrap();
    }

    // It takes a little time for the ls command to reflect newly created entries if not synced.
    // it's not a problem in real world.
    sync_fs().await;

    let mut read_back = Vec::new();
    for file_handle in store.list_metadata_files().await.unwrap() {
        let mut buf = String::new();
        store
            .open_for_read(&file_handle)
            .await
            .unwrap()
            .read_to_string(&mut buf)
            .await
            .unwrap();
        read_back.extend(
            buf.lines()
                .map(TextLine::new)
                .collect::<Result<Vec<_>>>()
                .unwrap()
                .into_iter(),
        )
    }
    read_back.sort();

    let expected = input
        .into_iter()
        .map(|(_name, content)| content)
        .sorted()
        .collect::<Vec<_>>();

    assert_eq!(read_back, expected)
}

pub fn arb_metadata_files() -> impl Strategy<Value = Vec<(ShellSafeName, TextLine)>> {
    vec(any::<(ShellSafeName, TextLine)>(), 0..10)
}

async fn sync_fs() {
    tokio::process::Command::new("sync")
        .stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn()
        .unwrap()
        .await
        .unwrap();
}
<|endoftext|>


<commit_before>#![feature(asm,no_std,lang_items,core)]
#![no_std]
#![crate_name="kernel"]

#![allow(unused_must_use)]

#[macro_use]
extern crate core;

use core::prelude::*;
use core::fmt::Write;

macro_rules! println {
    ($($arg:tt)*) => (::io::println_formatted(format_args!($($arg)*)))
}

mod lang;
pub mod io;
mod dev;
mod mem;

#[allow(dead_code)]
#[repr(u32)]
#[derive(Debug)]
#[derive(PartialEq)]
#[derive(Eq)]
enum EfiMemoryType {
	EfiReservedMemoryType,
	EfiLoaderCode,
	EfiLoaderData,
	EfiBootServicesCode,
	EfiBootServicesData,
	EfiRuntimeServicesCode,
	EfiRuntimeServicesData,
	EfiConventionalMemory,
	EfiUnusableMemory,
	EfiACPIReclaimMemory,
	EfiACPIMemoryNVS,
	EfiMemoryMappedIO,
	EfiMemoryMappedIOPortSpace,
	EfiPalCode,
	EfiMaxMemoryType,
}

#[repr(C)]
struct EfiMemoryDescriptor {
    type_: EfiMemoryType,
    phys_start: u64,
    virt_start: u64,
    npages: u64,
    attrs: u64,
}

#[repr(C)]
pub struct BootProto {
    mem_map: *const EfiMemoryDescriptor,
    map_size: u64,
    map_ent_size: u64
}

struct BootProtoIter {
    map: *const EfiMemoryDescriptor,
    size: u64,
    ent_size: u64,
    idx: u64,
}

pub static mut SP: Option<dev::serial::SerialPort> = None;

impl Iterator for BootProtoIter {
    type Item = *const EfiMemoryDescriptor;
    fn next(&mut self) -> Option<*const EfiMemoryDescriptor> {
        if self.idx * self.ent_size >= self.size {
            None
        } else {
            let r = Some((self.map as u64 + (self.idx*self.ent_size)) as *const EfiMemoryDescriptor);
            self.idx += 1;
            r
        }
    }
}

#[no_mangle]
pub fn main(bootproto: *const BootProto) {
    let sp = dev::serial::SerialPort::init(0x3F8);
    unsafe {
        SP = Some(sp);
    }

    println!("KERNEL START");

    let mut max_rg_sz = 0usize;
    let mut max_rg_ptr = 0usize;

    unsafe {
        let bpi = BootProtoIter { map: (*bootproto).mem_map, size: (*bootproto).map_size, ent_size: (*bootproto).map_ent_size, idx: 0};

        for region in bpi {
            println!("{:?} from {:x} -> {:x} (sz {:x})", (*region).type_, (*region).phys_start, (*region).phys_start+((*region).npages*4096), (*region).npages*4096);
            if (*region).type_ == EfiMemoryType::EfiConventionalMemory && ((*region).npages*4096) as usize > max_rg_sz {
                max_rg_sz = ((*region).npages*4096) as usize;
                max_rg_ptr = (*region).phys_start as usize;
            }
        }
    }

    let maxmem = unsafe {
        let bpi = BootProtoIter { map: (*bootproto).mem_map, size: (*bootproto).map_size, ent_size: (*bootproto).map_ent_size, idx:0 };
        let last = bpi.last().unwrap();
        ((*last).phys_start+((*last).npages*4096)) as usize
    };

    println!("maxmem is {:x}", maxmem);

    let mut heap = mem::Heap::new(maxmem, max_rg_ptr, max_rg_sz);
    let mut pg5 = 0;
    println!("Heap testing: ");
    for i in (0..15) {
        println!("Allocating span of 1024 pages (4M)...");
        match heap.alloc_pages(1024) {
            Some(page) => {
                println!("...success, allocated page {:x} at {:x}", page, page << 12);
                if i == 5 {
                    pg5 = page;
                };
            },
            None => {
                println!("...failed (out of memory?)");
            }
        };
    }

    println!("Deallocating allocation 5 (page {:x} at {:x})...", pg5, pg5 << 12);

    heap.clear_used_range(pg5, 1024);

    println!("Allocating a 2048 (8M) span (order 11)...");

    match heap.alloc_pages(2048) {
        Some(page) => println!("...success, allocated page {:x} at {:x}", page, page << 12),
        None => println!("...failed."),
    };

    println!("Allocating one more 1024 (4M) span (order 10)...");

    match heap.alloc_pages(1024) {
        Some(page) => println!("...success, allocated page {:x} at {:x}", page, page << 12),
        None => println!("...failed."),
    };

    panic!("Reached end of main");
}
<commit_msg>Prettily print maxmem in MB.<commit_after>#![feature(asm,no_std,lang_items,core)]
#![no_std]
#![crate_name="kernel"]

#![allow(unused_must_use)]

#[macro_use]
extern crate core;

use core::prelude::*;
use core::fmt::Write;

macro_rules! println {
    ($($arg:tt)*) => (::io::println_formatted(format_args!($($arg)*)))
}

mod lang;
pub mod io;
mod dev;
mod mem;

#[allow(dead_code)]
#[repr(u32)]
#[derive(Debug)]
#[derive(PartialEq)]
#[derive(Eq)]
enum EfiMemoryType {
	EfiReservedMemoryType,
	EfiLoaderCode,
	EfiLoaderData,
	EfiBootServicesCode,
	EfiBootServicesData,
	EfiRuntimeServicesCode,
	EfiRuntimeServicesData,
	EfiConventionalMemory,
	EfiUnusableMemory,
	EfiACPIReclaimMemory,
	EfiACPIMemoryNVS,
	EfiMemoryMappedIO,
	EfiMemoryMappedIOPortSpace,
	EfiPalCode,
	EfiMaxMemoryType,
}

#[repr(C)]
struct EfiMemoryDescriptor {
    type_: EfiMemoryType,
    phys_start: u64,
    virt_start: u64,
    npages: u64,
    attrs: u64,
}

#[repr(C)]
pub struct BootProto {
    mem_map: *const EfiMemoryDescriptor,
    map_size: u64,
    map_ent_size: u64
}

struct BootProtoIter {
    map: *const EfiMemoryDescriptor,
    size: u64,
    ent_size: u64,
    idx: u64,
}

pub static mut SP: Option<dev::serial::SerialPort> = None;

impl Iterator for BootProtoIter {
    type Item = *const EfiMemoryDescriptor;
    fn next(&mut self) -> Option<*const EfiMemoryDescriptor> {
        if self.idx * self.ent_size >= self.size {
            None
        } else {
            let r = Some((self.map as u64 + (self.idx*self.ent_size)) as *const EfiMemoryDescriptor);
            self.idx += 1;
            r
        }
    }
}

#[no_mangle]
pub fn main(bootproto: *const BootProto) {
    let sp = dev::serial::SerialPort::init(0x3F8);
    unsafe {
        SP = Some(sp);
    }

    println!("KERNEL START");

    let mut max_rg_sz = 0usize;
    let mut max_rg_ptr = 0usize;

    unsafe {
        let bpi = BootProtoIter { map: (*bootproto).mem_map, size: (*bootproto).map_size, ent_size: (*bootproto).map_ent_size, idx: 0};

        for region in bpi {
            println!("{:?} from {:x} -> {:x} (sz {:x})", (*region).type_, (*region).phys_start, (*region).phys_start+((*region).npages*4096), (*region).npages*4096);
            if (*region).type_ == EfiMemoryType::EfiConventionalMemory && ((*region).npages*4096) as usize > max_rg_sz {
                max_rg_sz = ((*region).npages*4096) as usize;
                max_rg_ptr = (*region).phys_start as usize;
            }
        }
    }

    let maxmem = unsafe {
        let bpi = BootProtoIter { map: (*bootproto).mem_map, size: (*bootproto).map_size, ent_size: (*bootproto).map_ent_size, idx:0 };
        let last = bpi.last().unwrap();
        ((*last).phys_start+((*last).npages*4096)) as usize
    };

    println!("maxmem is {:x} ({} MB)", maxmem, maxmem/1024/1024);

    let mut heap = mem::Heap::new(maxmem, max_rg_ptr, max_rg_sz);
    let mut pg5 = 0;
    println!("Heap testing: ");
    for i in (0..15) {
        println!("Allocating span of 1024 pages (4M)...");
        match heap.alloc_pages(1024) {
            Some(page) => {
                println!("...success, allocated page {:x} at {:x}", page, page << 12);
                if i == 5 {
                    pg5 = page;
                };
            },
            None => {
                println!("...failed (out of memory?)");
            }
        };
    }

    println!("Deallocating allocation 5 (page {:x} at {:x})...", pg5, pg5 << 12);

    heap.clear_used_range(pg5, 1024);

    println!("Allocating a 2048 (8M) span (order 11)...");

    match heap.alloc_pages(2048) {
        Some(page) => println!("...success, allocated page {:x} at {:x}", page, page << 12),
        None => println!("...failed."),
    };

    println!("Allocating one more 1024 (4M) span (order 10)...");

    match heap.alloc_pages(1024) {
        Some(page) => println!("...success, allocated page {:x} at {:x}", page, page << 12),
        None => println!("...failed."),
    };

    panic!("Reached end of main");
}
<|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/. */

//! This module contains shared types and messages for use by devtools/script.
//! The traits are here instead of in script so that the devtools crate can be
//! modified independently of the rest of Servo.

#![crate_name = "devtools_traits"]
#![crate_type = "rlib"]

#![allow(non_snake_case)]
#![deny(unsafe_code)]

#![feature(custom_derive, plugin)]
#![plugin(heapsize_plugin, serde_macros)]

#[allow(unused_extern_crates)]
#[macro_use]
extern crate bitflags;
extern crate heapsize;
extern crate hyper;
extern crate ipc_channel;
extern crate msg;
extern crate serde;
extern crate time;
extern crate url;

use hyper::header::Headers;
use hyper::http::RawStatus;
use hyper::method::Method;
use ipc_channel::ipc::IpcSender;
use msg::constellation_msg::PipelineId;
use std::net::TcpStream;
use time::Duration;
use time::Tm;
use url::Url;

// Information would be attached to NewGlobal to be received and show in devtools.
// Extend these fields if we need more information.
#[derive(Deserialize, Serialize)]
pub struct DevtoolsPageInfo {
    pub title: String,
    pub url: Url
}

#[derive(Deserialize, HeapSizeOf, Serialize, Clone)]
pub struct CSSError {
    pub filename: String,
    pub line: usize,
    pub column: usize,
    pub msg: String
}

/// Messages to instruct the devtools server to update its known actors/state
/// according to changes in the browser.
pub enum DevtoolsControlMsg {
    /// Messages from threads in the chrome process (resource/constellation/devtools)
    FromChrome(ChromeToDevtoolsControlMsg),
    /// Messages from script threads
    FromScript(ScriptToDevtoolsControlMsg),
}

/// Events that the devtools server must act upon.
pub enum ChromeToDevtoolsControlMsg {
    /// A new client has connected to the server.
    AddClient(TcpStream),
    /// The browser is shutting down.
    ServerExitMsg,
    /// A network event occurred (request, reply, etc.). The actor with the
    /// provided name should be notified.
    NetworkEvent(String, NetworkEvent),
}

#[derive(Deserialize, Serialize)]
/// Events that the devtools server must act upon.
pub enum ScriptToDevtoolsControlMsg {
    /// A new global object was created, associated with a particular pipeline.
    /// The means of communicating directly with it are provided.
    NewGlobal((PipelineId, Option<WorkerId>),
              IpcSender<DevtoolScriptControlMsg>,
              DevtoolsPageInfo),
    /// A particular page has invoked the console API.
    ConsoleAPI(PipelineId, ConsoleMessage, Option<WorkerId>),
    /// An animation frame with the given timestamp was processed in a script thread.
    /// The actor with the provided name should be notified.
    FramerateTick(String, f64),

    /// Report a CSS parse error for the given pipeline
    ReportCSSError(PipelineId, CSSError),
}

/// Serialized JS return values
/// TODO: generalize this beyond the EvaluateJS message?
#[derive(Deserialize, Serialize)]
pub enum EvaluateJSReply {
    VoidValue,
    NullValue,
    BooleanValue(bool),
    NumberValue(f64),
    StringValue(String),
    ActorValue { class: String, uuid: String },
}

#[derive(Deserialize, Serialize)]
pub struct AttrInfo {
    pub namespace: String,
    pub name: String,
    pub value: String,
}

#[derive(Deserialize, Serialize)]
pub struct NodeInfo {
    pub uniqueId: String,
    pub baseURI: String,
    pub parent: String,
    pub nodeType: u16,
    pub namespaceURI: String,
    pub nodeName: String,
    pub numChildren: usize,

    pub name: String,
    pub publicId: String,
    pub systemId: String,

    pub attrs: Vec<AttrInfo>,

    pub isDocumentElement: bool,

    pub shortValue: String,
    pub incompleteValue: bool,
}

pub struct StartedTimelineMarker {
    name: String,
    start_time: PreciseTime,
    start_stack: Option<Vec<()>>,
}

#[derive(Deserialize, Serialize)]
pub struct TimelineMarker {
    pub name: String,
    pub start_time: PreciseTime,
    pub start_stack: Option<Vec<()>>,
    pub end_time: PreciseTime,
    pub end_stack: Option<Vec<()>>,
}

#[derive(PartialEq, Eq, Hash, Clone, Deserialize, Serialize)]
pub enum TimelineMarkerType {
    Reflow,
    DOMEvent,
}

/// The properties of a DOM node as computed by layout.
#[derive(Deserialize, Serialize)]
pub struct ComputedNodeLayout {
    pub display: String,
    pub position: String,
    pub zIndex: String,
    pub boxSizing: String,

    pub autoMargins: AutoMargins,
    pub marginTop: String,
    pub marginRight: String,
    pub marginBottom: String,
    pub marginLeft: String,

    pub borderTopWidth: String,
    pub borderRightWidth: String,
    pub borderBottomWidth: String,
    pub borderLeftWidth: String,

    pub paddingTop: String,
    pub paddingRight: String,
    pub paddingBottom: String,
    pub paddingLeft: String,

    pub width: f32,
    pub height: f32,
}

#[derive(Deserialize, Serialize)]
pub struct AutoMargins {
    pub top: bool,
    pub right: bool,
    pub bottom: bool,
    pub left: bool,
}

/// Messages to process in a particular script thread, as instructed by a devtools client.
#[derive(Deserialize, Serialize)]
pub enum DevtoolScriptControlMsg {
    /// Evaluate a JS snippet in the context of the global for the given pipeline.
    EvaluateJS(PipelineId, String, IpcSender<EvaluateJSReply>),
    /// Retrieve the details of the root node (ie. the document) for the given pipeline.
    GetRootNode(PipelineId, IpcSender<Option<NodeInfo>>),
    /// Retrieve the details of the document element for the given pipeline.
    GetDocumentElement(PipelineId, IpcSender<Option<NodeInfo>>),
    /// Retrieve the details of the child nodes of the given node in the given pipeline.
    GetChildren(PipelineId, String, IpcSender<Option<Vec<NodeInfo>>>),
    /// Retrieve the computed layout properties of the given node in the given pipeline.
    GetLayout(PipelineId, String, IpcSender<Option<ComputedNodeLayout>>),
    /// Retrieve all stored console messages for the given pipeline.
    GetCachedMessages(PipelineId, CachedConsoleMessageTypes, IpcSender<Vec<CachedConsoleMessage>>),
    /// Update a given node's attributes with a list of modifications.
    ModifyAttribute(PipelineId, String, Vec<Modification>),
    /// Request live console messages for a given pipeline (true if desired, false otherwise).
    WantsLiveNotifications(PipelineId, bool),
    /// Request live notifications for a given set of timeline events for a given pipeline.
    SetTimelineMarkers(PipelineId, Vec<TimelineMarkerType>, IpcSender<TimelineMarker>),
    /// Withdraw request for live timeline notifications for a given pipeline.
    DropTimelineMarkers(PipelineId, Vec<TimelineMarkerType>),
    /// Request a callback directed at the given actor name from the next animation frame
    /// executed in the given pipeline.
    RequestAnimationFrame(PipelineId, String),
    /// Direct the given pipeline to reload the current page.
    Reload(PipelineId),
}

#[derive(Deserialize, Serialize)]
pub struct Modification {
    pub attributeName: String,
    pub newValue: Option<String>,
}

#[derive(Clone, Deserialize, Serialize)]
pub enum LogLevel {
    Log,
    Debug,
    Info,
    Warn,
    Error,
}

#[derive(Clone, Deserialize, Serialize)]
pub struct ConsoleMessage {
    pub message: String,
    pub logLevel: LogLevel,
    pub filename: String,
    pub lineNumber: usize,
    pub columnNumber: usize,
}

bitflags! {
    #[derive(Deserialize, Serialize)]
    pub flags CachedConsoleMessageTypes: u8 {
        const PAGE_ERROR  = 1 << 0,
        const CONSOLE_API = 1 << 1,
    }
}

#[derive(Deserialize, Serialize)]
pub struct PageError {
    #[serde(rename = "type")]
    pub type_: String,
    pub errorMessage: String,
    pub sourceName: String,
    pub lineText: String,
    pub lineNumber: u32,
    pub columnNumber: u32,
    pub category: String,
    pub timeStamp: u64,
    pub error: bool,
    pub warning: bool,
    pub exception: bool,
    pub strict: bool,
    pub private: bool,
}

#[derive(Deserialize, Serialize)]
pub struct ConsoleAPI {
    #[serde(rename = "type")]
    pub type_: String,
    pub level: String,
    pub filename: String,
    pub lineNumber: u32,
    pub functionName: String,
    pub timeStamp: u64,
    pub private: bool,
    pub arguments: Vec<String>,
}

#[derive(Deserialize, Serialize)]
pub enum CachedConsoleMessage {
    PageError(PageError),
    ConsoleAPI(ConsoleAPI),
}

#[derive(Debug, PartialEq)]
pub struct HttpRequest {
    pub url: Url,
    pub method: Method,
    pub headers: Headers,
    pub body: Option<Vec<u8>>,
    pub pipeline_id: PipelineId,
    pub startedDateTime: Tm,
    pub timeStamp: i64,
    pub connect_time: u64,
    pub send_time: u64,
    pub is_xhr: bool,
}

#[derive(Debug, PartialEq)]
pub struct HttpResponse {
    pub headers: Option<Headers>,
    pub status: Option<RawStatus>,
    pub body: Option<Vec<u8>>,
    pub pipeline_id: PipelineId,
}

pub enum NetworkEvent {
    HttpRequest(HttpRequest),
    HttpResponse(HttpResponse),
}

impl TimelineMarker {
    pub fn start(name: String) -> StartedTimelineMarker {
        StartedTimelineMarker {
            name: name,
            start_time: PreciseTime::now(),
            start_stack: None,
        }
    }
}

impl StartedTimelineMarker {
    pub fn end(self) -> TimelineMarker {
        TimelineMarker {
            name: self.name,
            start_time: self.start_time,
            start_stack: self.start_stack,
            end_time: PreciseTime::now(),
            end_stack: None,
        }
    }
}

/// A replacement for `time::PreciseTime` that isn't opaque, so we can serialize it.
///
/// The reason why this doesn't go upstream is that `time` is slated to be part of Rust's standard
/// library, which definitely can't have any dependencies on `serde`. But `serde` can't implement
/// `Deserialize` and `Serialize` itself, because `time::PreciseTime` is opaque! A Catch-22. So I'm
/// duplicating the definition here.
#[derive(Copy, Clone, Deserialize, Serialize)]
pub struct PreciseTime(u64);

impl PreciseTime {
    pub fn now() -> PreciseTime {
        PreciseTime(time::precise_time_ns())
    }

    pub fn to(&self, later: PreciseTime) -> Duration {
        Duration::nanoseconds((later.0 - self.0) as i64)
    }
}

#[derive(Clone, PartialEq, Eq, Copy, Hash, Debug, Deserialize, Serialize, HeapSizeOf)]
pub struct WorkerId(pub u32);
<commit_msg>Console message packets should have a '_type' attribute<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/. */

//! This module contains shared types and messages for use by devtools/script.
//! The traits are here instead of in script so that the devtools crate can be
//! modified independently of the rest of Servo.

#![crate_name = "devtools_traits"]
#![crate_type = "rlib"]

#![allow(non_snake_case)]
#![deny(unsafe_code)]

#![feature(custom_derive, plugin)]
#![plugin(heapsize_plugin, serde_macros)]

#[allow(unused_extern_crates)]
#[macro_use]
extern crate bitflags;
extern crate heapsize;
extern crate hyper;
extern crate ipc_channel;
extern crate msg;
extern crate serde;
extern crate time;
extern crate url;

use hyper::header::Headers;
use hyper::http::RawStatus;
use hyper::method::Method;
use ipc_channel::ipc::IpcSender;
use msg::constellation_msg::PipelineId;
use std::net::TcpStream;
use time::Duration;
use time::Tm;
use url::Url;

// Information would be attached to NewGlobal to be received and show in devtools.
// Extend these fields if we need more information.
#[derive(Deserialize, Serialize)]
pub struct DevtoolsPageInfo {
    pub title: String,
    pub url: Url
}

#[derive(Deserialize, HeapSizeOf, Serialize, Clone)]
pub struct CSSError {
    pub filename: String,
    pub line: usize,
    pub column: usize,
    pub msg: String
}

/// Messages to instruct the devtools server to update its known actors/state
/// according to changes in the browser.
pub enum DevtoolsControlMsg {
    /// Messages from threads in the chrome process (resource/constellation/devtools)
    FromChrome(ChromeToDevtoolsControlMsg),
    /// Messages from script threads
    FromScript(ScriptToDevtoolsControlMsg),
}

/// Events that the devtools server must act upon.
pub enum ChromeToDevtoolsControlMsg {
    /// A new client has connected to the server.
    AddClient(TcpStream),
    /// The browser is shutting down.
    ServerExitMsg,
    /// A network event occurred (request, reply, etc.). The actor with the
    /// provided name should be notified.
    NetworkEvent(String, NetworkEvent),
}

#[derive(Deserialize, Serialize)]
/// Events that the devtools server must act upon.
pub enum ScriptToDevtoolsControlMsg {
    /// A new global object was created, associated with a particular pipeline.
    /// The means of communicating directly with it are provided.
    NewGlobal((PipelineId, Option<WorkerId>),
              IpcSender<DevtoolScriptControlMsg>,
              DevtoolsPageInfo),
    /// A particular page has invoked the console API.
    ConsoleAPI(PipelineId, ConsoleMessage, Option<WorkerId>),
    /// An animation frame with the given timestamp was processed in a script thread.
    /// The actor with the provided name should be notified.
    FramerateTick(String, f64),

    /// Report a CSS parse error for the given pipeline
    ReportCSSError(PipelineId, CSSError),
}

/// Serialized JS return values
/// TODO: generalize this beyond the EvaluateJS message?
#[derive(Deserialize, Serialize)]
pub enum EvaluateJSReply {
    VoidValue,
    NullValue,
    BooleanValue(bool),
    NumberValue(f64),
    StringValue(String),
    ActorValue { class: String, uuid: String },
}

#[derive(Deserialize, Serialize)]
pub struct AttrInfo {
    pub namespace: String,
    pub name: String,
    pub value: String,
}

#[derive(Deserialize, Serialize)]
pub struct NodeInfo {
    pub uniqueId: String,
    pub baseURI: String,
    pub parent: String,
    pub nodeType: u16,
    pub namespaceURI: String,
    pub nodeName: String,
    pub numChildren: usize,

    pub name: String,
    pub publicId: String,
    pub systemId: String,

    pub attrs: Vec<AttrInfo>,

    pub isDocumentElement: bool,

    pub shortValue: String,
    pub incompleteValue: bool,
}

pub struct StartedTimelineMarker {
    name: String,
    start_time: PreciseTime,
    start_stack: Option<Vec<()>>,
}

#[derive(Deserialize, Serialize)]
pub struct TimelineMarker {
    pub name: String,
    pub start_time: PreciseTime,
    pub start_stack: Option<Vec<()>>,
    pub end_time: PreciseTime,
    pub end_stack: Option<Vec<()>>,
}

#[derive(PartialEq, Eq, Hash, Clone, Deserialize, Serialize)]
pub enum TimelineMarkerType {
    Reflow,
    DOMEvent,
}

/// The properties of a DOM node as computed by layout.
#[derive(Deserialize, Serialize)]
pub struct ComputedNodeLayout {
    pub display: String,
    pub position: String,
    pub zIndex: String,
    pub boxSizing: String,

    pub autoMargins: AutoMargins,
    pub marginTop: String,
    pub marginRight: String,
    pub marginBottom: String,
    pub marginLeft: String,

    pub borderTopWidth: String,
    pub borderRightWidth: String,
    pub borderBottomWidth: String,
    pub borderLeftWidth: String,

    pub paddingTop: String,
    pub paddingRight: String,
    pub paddingBottom: String,
    pub paddingLeft: String,

    pub width: f32,
    pub height: f32,
}

#[derive(Deserialize, Serialize)]
pub struct AutoMargins {
    pub top: bool,
    pub right: bool,
    pub bottom: bool,
    pub left: bool,
}

/// Messages to process in a particular script thread, as instructed by a devtools client.
#[derive(Deserialize, Serialize)]
pub enum DevtoolScriptControlMsg {
    /// Evaluate a JS snippet in the context of the global for the given pipeline.
    EvaluateJS(PipelineId, String, IpcSender<EvaluateJSReply>),
    /// Retrieve the details of the root node (ie. the document) for the given pipeline.
    GetRootNode(PipelineId, IpcSender<Option<NodeInfo>>),
    /// Retrieve the details of the document element for the given pipeline.
    GetDocumentElement(PipelineId, IpcSender<Option<NodeInfo>>),
    /// Retrieve the details of the child nodes of the given node in the given pipeline.
    GetChildren(PipelineId, String, IpcSender<Option<Vec<NodeInfo>>>),
    /// Retrieve the computed layout properties of the given node in the given pipeline.
    GetLayout(PipelineId, String, IpcSender<Option<ComputedNodeLayout>>),
    /// Retrieve all stored console messages for the given pipeline.
    GetCachedMessages(PipelineId, CachedConsoleMessageTypes, IpcSender<Vec<CachedConsoleMessage>>),
    /// Update a given node's attributes with a list of modifications.
    ModifyAttribute(PipelineId, String, Vec<Modification>),
    /// Request live console messages for a given pipeline (true if desired, false otherwise).
    WantsLiveNotifications(PipelineId, bool),
    /// Request live notifications for a given set of timeline events for a given pipeline.
    SetTimelineMarkers(PipelineId, Vec<TimelineMarkerType>, IpcSender<TimelineMarker>),
    /// Withdraw request for live timeline notifications for a given pipeline.
    DropTimelineMarkers(PipelineId, Vec<TimelineMarkerType>),
    /// Request a callback directed at the given actor name from the next animation frame
    /// executed in the given pipeline.
    RequestAnimationFrame(PipelineId, String),
    /// Direct the given pipeline to reload the current page.
    Reload(PipelineId),
}

#[derive(Deserialize, Serialize)]
pub struct Modification {
    pub attributeName: String,
    pub newValue: Option<String>,
}

#[derive(Clone, Deserialize, Serialize)]
pub enum LogLevel {
    Log,
    Debug,
    Info,
    Warn,
    Error,
}

#[derive(Clone, Deserialize, Serialize)]
pub struct ConsoleMessage {
    pub message: String,
    pub logLevel: LogLevel,
    pub filename: String,
    pub lineNumber: usize,
    pub columnNumber: usize,
}

bitflags! {
    #[derive(Deserialize, Serialize)]
    pub flags CachedConsoleMessageTypes: u8 {
        const PAGE_ERROR  = 1 << 0,
        const CONSOLE_API = 1 << 1,
    }
}

#[derive(Deserialize, Serialize)]
pub struct PageError {
    #[serde(rename = "_type")]
    pub type_: String,
    pub errorMessage: String,
    pub sourceName: String,
    pub lineText: String,
    pub lineNumber: u32,
    pub columnNumber: u32,
    pub category: String,
    pub timeStamp: u64,
    pub error: bool,
    pub warning: bool,
    pub exception: bool,
    pub strict: bool,
    pub private: bool,
}

#[derive(Deserialize, Serialize)]
pub struct ConsoleAPI {
    #[serde(rename = "_type")]
    pub type_: String,
    pub level: String,
    pub filename: String,
    pub lineNumber: u32,
    pub functionName: String,
    pub timeStamp: u64,
    pub private: bool,
    pub arguments: Vec<String>,
}

#[derive(Deserialize, Serialize)]
pub enum CachedConsoleMessage {
    PageError(PageError),
    ConsoleAPI(ConsoleAPI),
}

#[derive(Debug, PartialEq)]
pub struct HttpRequest {
    pub url: Url,
    pub method: Method,
    pub headers: Headers,
    pub body: Option<Vec<u8>>,
    pub pipeline_id: PipelineId,
    pub startedDateTime: Tm,
    pub timeStamp: i64,
    pub connect_time: u64,
    pub send_time: u64,
    pub is_xhr: bool,
}

#[derive(Debug, PartialEq)]
pub struct HttpResponse {
    pub headers: Option<Headers>,
    pub status: Option<RawStatus>,
    pub body: Option<Vec<u8>>,
    pub pipeline_id: PipelineId,
}

pub enum NetworkEvent {
    HttpRequest(HttpRequest),
    HttpResponse(HttpResponse),
}

impl TimelineMarker {
    pub fn start(name: String) -> StartedTimelineMarker {
        StartedTimelineMarker {
            name: name,
            start_time: PreciseTime::now(),
            start_stack: None,
        }
    }
}

impl StartedTimelineMarker {
    pub fn end(self) -> TimelineMarker {
        TimelineMarker {
            name: self.name,
            start_time: self.start_time,
            start_stack: self.start_stack,
            end_time: PreciseTime::now(),
            end_stack: None,
        }
    }
}

/// A replacement for `time::PreciseTime` that isn't opaque, so we can serialize it.
///
/// The reason why this doesn't go upstream is that `time` is slated to be part of Rust's standard
/// library, which definitely can't have any dependencies on `serde`. But `serde` can't implement
/// `Deserialize` and `Serialize` itself, because `time::PreciseTime` is opaque! A Catch-22. So I'm
/// duplicating the definition here.
#[derive(Copy, Clone, Deserialize, Serialize)]
pub struct PreciseTime(u64);

impl PreciseTime {
    pub fn now() -> PreciseTime {
        PreciseTime(time::precise_time_ns())
    }

    pub fn to(&self, later: PreciseTime) -> Duration {
        Duration::nanoseconds((later.0 - self.0) as i64)
    }
}

#[derive(Clone, PartialEq, Eq, Copy, Hash, Debug, Deserialize, Serialize, HeapSizeOf)]
pub struct WorkerId(pub u32);
<|endoftext|>


<commit_before>//! Define routes for exposing the contents of the application's
//! rendering context.

use crate::{config,
            error::Result};
use actix_web::{web,
                HttpRequest,
                HttpResponse};
use serde_json;
use std::{fs,
          path::{Components,
                 Path,
                 PathBuf}};

/// Show render context rooted at `path`
#[allow(clippy::needless_pass_by_value)] // Required by actix-web API
pub fn show(config: web::Data<config::Config>,
            req: HttpRequest)
            -> actix_web::Result<HttpResponse> {
    let path = req.match_info()
                  .get("path")
                  .map(PathBuf::from)
                  .unwrap_or_default();
    let json =
        extract_data(&config.render_context_file, &path).map_err(actix_web::error::ErrorBadRequest)?;

    if let Some(json) = json {
        Ok(HttpResponse::Ok().json(json))
    } else {
        Ok(HttpResponse::NotFound().finish())
    }
}

////////////////////////////////////////////////////////////////////////

fn extract_data<P>(render_context_file: P, path: P) -> Result<Option<serde_json::Value>>
    where P: AsRef<Path>
{
    let data = read_json(render_context_file)?;
    lookup(data, path.as_ref().components())
}

/// Read a file into a JSON value
fn read_json<P>(path: P) -> Result<serde_json::Value>
    where P: AsRef<Path>
{
    let contents = fs::read_to_string(path)?;
    serde_json::from_str(&contents).map_err(|e| e.into())
}

/// Recursively descend through a JSON structure, based on the path
/// provided in `keys`
fn lookup(data: serde_json::Value, keys: Components) -> Result<Option<serde_json::Value>> {
    let mut result = data;
    for component in keys {
        let key: &str = &component.as_os_str().to_string_lossy();

        // For arrays, try to coerce key to an integer and do a lookup
        // that way
        let lookup_result = if result.is_array() {
            result.get(key.parse::<usize>()?)
        } else {
            result.get(key)
        };

        if let Some(stuff) = lookup_result {
            result = stuff.clone(); // eww
        } else {
            return Ok(None);
        }
    }
    Ok(Some(result))
}
<commit_msg>[PR Feedback] Use JSON pointers instead of "creative" PathBufs<commit_after>//! Define routes for exposing the contents of the application's
//! rendering context.

use crate::{config,
            error::Result};
use actix_web::{web,
                HttpRequest,
                HttpResponse};
use serde_json;
use std::{borrow::Cow,
          fs,
          path::Path};

/// Show render context rooted at `path`
#[allow(clippy::needless_pass_by_value)] // Required by actix-web API
pub fn show(config: web::Data<config::Config>,
            req: HttpRequest)
            -> actix_web::Result<HttpResponse> {
    // A JSON pointer of "" means "everything". Pointers starting with
    // "/" describe paths into the structure. We'll chop off any
    // trailing "/" since that will end up looking for an item with a
    // key of "", which we're just not going to deal with.
    let pointer = match req.match_info().get("path") {
        None | Some("") => Cow::Borrowed(""),
        Some(path) => Cow::Owned(format!("/{}", path.trim_end_matches('/'))),
    };
    let json = read_json(&config.render_context_file).map_err(actix_web::error::ErrorBadRequest)?;
    if let Some(value) = json.pointer(&pointer) {
        Ok(HttpResponse::Ok().json(value))
    } else {
        Ok(HttpResponse::NotFound().finish())
    }
}

////////////////////////////////////////////////////////////////////////

/// Read a file into a JSON value
fn read_json<P>(path: P) -> Result<serde_json::Value>
    where P: AsRef<Path>
{
    let contents = fs::read_to_string(path)?;
    serde_json::from_str(&contents).map_err(|e| e.into())
}
<|endoftext|>


<commit_before>#![crate_type = "bin"]

extern crate rgtk;

use rgtk::*;
use rgtk::gtk::signals::{Clicked, KeyPressEvent, DeleteEvent};
use rgtk::gdk::enums::modifier_type;

/// Expands to its argument if GTK+ 3.10 support is configured and to `()` otherwise
#[macro_export]
#[cfg(not(any(feature = "GTK_3_10", feature = "GTK_3_12", feature = "GTK_3_14")))]
macro_rules! with_gtk_3_10 {
    ($ex:expr) => (
        ()
    );
    ($bl:block) => {
        ()
    }
}

/// Expands to its argument if GTK+ 3.10 support is configured and to `()` otherwise
#[macro_export]
#[cfg(any(feature = "GTK_3_10", feature = "GTK_3_12", feature = "GTK_3_14"))]
macro_rules! with_gtk_3_10 {
    ($ex:expr) => (
        $ex
    );
    ($bl:block) => {
        $bl
    }
}

fn main() {
    gtk::init();
    println!("Major: {}, Minor: {}", gtk::get_major_version(), gtk::get_minor_version());
    let mut window = gtk::Window::new(gtk::WindowType::TopLevel).unwrap();
    let mut frame = gtk::Frame::new(Some("Yep a frame")).unwrap();
    let mut _box = gtk::Box::new(gtk::Orientation::Horizontal, 10).unwrap();
    let mut v_box = gtk::Box::new(gtk::Orientation::Horizontal, 10).unwrap();
    let mut button_box = gtk::ButtonBox::new(gtk::Orientation::Horizontal).unwrap();
    let mut label = gtk::Label::new("Yeah a wonderful label too !").unwrap();
    let button = gtk::Button::new_with_label("Whattttt a button !").unwrap();
    let button_recent = gtk::Button::new_with_label("Choose a recent one !").unwrap();
    let button_font = gtk::Button::new_with_label("Choose a font !").unwrap();
    let app_button = gtk::Button::new_with_label("App ?").unwrap();
    let file_button = gtk::Button::new_with_label("file ?").unwrap();
    let font_button = gtk::FontButton::new().unwrap();
    let toggle_button = gtk::ToggleButton::new_with_label("Toggle Me !").unwrap();
    let check_button = gtk::CheckButton::new_with_label("Labeled check button").unwrap();
    let color_button = gtk::ColorButton::new().unwrap();
    let menu_button = with_gtk_3_10!(
        gtk::MenuButton::new().unwrap()
    );
    let link_button = gtk::LinkButton::new("www.rust-lang.org").unwrap();
    let mut volume_button = gtk::VolumeButton::new().unwrap();
    let mut entry = gtk::Entry::new().unwrap();
    let search_entry = with_gtk_3_10!(
        gtk::SearchEntry::new().unwrap()
    );
    let separator = gtk::Separator::new(gtk::Orientation::Horizontal).unwrap();
    let separator2 = gtk::Separator::new(gtk::Orientation::Horizontal).unwrap();
    let switch = gtk::Switch::new().unwrap();
    let mut switch2 = gtk::Switch::new().unwrap();
    let scale = gtk::Scale::new_with_range(gtk::Orientation::Horizontal, 0., 100., 1.).unwrap();
    let mut level_bar = with_gtk_3_10!(
        gtk::LevelBar::new_for_interval(0., 100.).unwrap()
    );
    let spin_button = gtk::SpinButton::new_with_range(0., 100., 1.).unwrap();
    let mut spinner = gtk::Spinner::new().unwrap();
    let image = gtk::Image::new_from_file("./test/resources/gtk.jpg").unwrap();
    let mut progress_bar = gtk::ProgressBar::new().unwrap();
    let arrow = gtk::Arrow::new(gtk::ArrowType::Right, gtk::ShadowType::EtchedOut).unwrap();
    let calendar = gtk::Calendar::new().unwrap();
    let mut info_bar = gtk::InfoBar::new().unwrap();
    let tmp_button = with_gtk_3_10!(
        gtk::Button::new_from_icon_name("edit-clear", gtk::IconSize::Button).unwrap()
    );

    println!("test");

    with_gtk_3_10! {{
        info_bar.show_close_button(true);
    }}

    /*info_bar.connect(signals::Response::new(|response_id| {
        info_bar.hide()
    }));*/ //TODO: Why does this not work?

    progress_bar.set_fraction(0.7);
    spinner.start();
    with_gtk_3_10! {{
        level_bar.set_value(37.);
    }}
    switch2.set_active(true);
    frame.set_border_width(10);
    _box.set_border_width(5);
    entry.set_placeholder("An Entry with a placeholder !");
    volume_button.set_orientation(gtk::Orientation::Horizontal);
    label.set_justify(gtk::Justification::Left);
    window.set_title("Yeah a beautiful window with rgtk !");
    window.set_window_position(gtk::WindowPosition::Center);
    window.add(&frame);

    Connect::connect(&button, Clicked::new(&mut ||{
        //entry.set_text("Clicked!".to_string());
        let dialog = gtk::MessageDialog::new_with_markup(None, gtk::DialogFlags::Modal, gtk::MessageType::Info,
            gtk::ButtonsType::OkCancel, "This is a trap !").unwrap();

        dialog.run();
    }));
    Connect::connect(&button_font, Clicked::new(&mut ||{
        let dialog = gtk::FontChooserDialog::new("Font chooser test", None).unwrap();

        dialog.run();
    }));
    Connect::connect(&button_recent, Clicked::new(&mut ||{
        let dialog = gtk::RecentChooserDialog::new("Recent chooser test", None).unwrap();

        dialog.run();
    }));
    Connect::connect(&file_button, Clicked::new(&mut ||{
        //entry.set_text("Clicked!".to_string());
        let dialog2 = gtk::FileChooserDialog::new("Choose a file", None, gtk::FileChooserAction::Open).unwrap();

        dialog2.run();
    }));
    Connect::connect(&app_button, Clicked::new(&mut ||{
        //entry.set_text("Clicked!".to_string());
        let dialog = gtk::AppChooserDialog::new_for_content_type(None, gtk::DialogFlags::Modal, "sh").unwrap();

        dialog.run();
    }));

    Connect::connect(&window, KeyPressEvent::new(&mut |key|{
        let keyval = unsafe { (*key).keyval };
        let keystate = unsafe { (*key).state };

        println!("key pressed: {} / {:?}", keyval, keystate);
        println!("text: {}", entry.get_text().unwrap());

        if keystate.intersects(modifier_type::ControlMask) {
            println!("You pressed Ctrl!");
        }
        false
    }));

    Connect::connect(&window, DeleteEvent::new(&mut |_|{
        gtk::main_quit();
        true
    }));

    frame.add(&_box);
    with_gtk_3_10! {{
        button_box.add(&tmp_button)
    }};
    button_box.add(&button);
    button_box.add(&button_font);
    button_box.add(&button_recent);
    button_box.add(&file_button);
    button_box.add(&app_button);
    button_box.add(&font_button);
    button_box.add(&toggle_button);
    button_box.add(&color_button);
    button_box.add(&volume_button);
    v_box.add(&switch);
    with_gtk_3_10! {{
        v_box.add(&menu_button);
    }}
    v_box.add(&switch2);
    v_box.add(&check_button);
    v_box.add(&link_button);
    v_box.add(&spin_button);
    _box.add(&info_bar);
    _box.add(&v_box);
    _box.add(&scale);
    with_gtk_3_10! {{
        _box.add(&level_bar);
    }}
    _box.add(&button_box);
    _box.add(&progress_bar);
    _box.add(&separator);
    _box.add(&label);
    _box.add(&entry);
    _box.add(&separator2);
    with_gtk_3_10! {{
        _box.add(&search_entry);
    }}
    _box.add(&spinner);
    _box.add(&image);
    _box.add(&arrow);
    _box.add(&calendar);
    _box.set_orientation(gtk::Orientation::Vertical);
    // window.set_decorated(false);
    window.set_decorated(true);
    window.show_all();
    gtk::main();
}
<commit_msg>Test the fixed AboutDialog and FileChooser APIs in gtktest<commit_after>#![crate_type = "bin"]

extern crate rgtk;

use rgtk::*;
use rgtk::gtk::signals::{Clicked, KeyPressEvent, DeleteEvent};
use rgtk::gdk::enums::modifier_type;

/// Expands to its argument if GTK+ 3.10 support is configured and to `()` otherwise
#[macro_export]
#[cfg(not(any(feature = "GTK_3_10", feature = "GTK_3_12", feature = "GTK_3_14")))]
macro_rules! with_gtk_3_10 {
    ($ex:expr) => (
        ()
    );
    ($bl:block) => {
        ()
    }
}

/// Expands to its argument if GTK+ 3.10 support is configured and to `()` otherwise
#[macro_export]
#[cfg(any(feature = "GTK_3_10", feature = "GTK_3_12", feature = "GTK_3_14"))]
macro_rules! with_gtk_3_10 {
    ($ex:expr) => (
        $ex
    );
    ($bl:block) => {
        $bl
    }
}

fn main() {
    gtk::init();
    println!("Major: {}, Minor: {}", gtk::get_major_version(), gtk::get_minor_version());
    let mut window = gtk::Window::new(gtk::WindowType::TopLevel).unwrap();
    let mut frame = gtk::Frame::new(Some("Yep a frame")).unwrap();
    let mut _box = gtk::Box::new(gtk::Orientation::Horizontal, 10).unwrap();
    let mut v_box = gtk::Box::new(gtk::Orientation::Horizontal, 10).unwrap();
    let mut button_box = gtk::ButtonBox::new(gtk::Orientation::Horizontal).unwrap();
    let mut label = gtk::Label::new("Yeah a wonderful label too !").unwrap();
    let button = gtk::Button::new_with_label("Whattttt a button !").unwrap();
    let button_recent = gtk::Button::new_with_label("Choose a recent one !").unwrap();
    let button_font = gtk::Button::new_with_label("Choose a font !").unwrap();
    let app_button = gtk::Button::new_with_label("App ?").unwrap();
    let file_button = gtk::Button::new_with_label("file ?").unwrap();
    let font_button = gtk::FontButton::new().unwrap();
    let toggle_button = gtk::ToggleButton::new_with_label("Toggle Me !").unwrap();
    let check_button = gtk::CheckButton::new_with_label("Labeled check button").unwrap();
    let color_button = gtk::ColorButton::new().unwrap();
    let menu_button = with_gtk_3_10!(
        gtk::MenuButton::new().unwrap()
    );
    let link_button = gtk::LinkButton::new("www.rust-lang.org").unwrap();
    let mut volume_button = gtk::VolumeButton::new().unwrap();
    let mut entry = gtk::Entry::new().unwrap();
    let search_entry = with_gtk_3_10!(
        gtk::SearchEntry::new().unwrap()
    );
    let separator = gtk::Separator::new(gtk::Orientation::Horizontal).unwrap();
    let separator2 = gtk::Separator::new(gtk::Orientation::Horizontal).unwrap();
    let switch = gtk::Switch::new().unwrap();
    let mut switch2 = gtk::Switch::new().unwrap();
    let scale = gtk::Scale::new_with_range(gtk::Orientation::Horizontal, 0., 100., 1.).unwrap();
    let mut level_bar = with_gtk_3_10!(
        gtk::LevelBar::new_for_interval(0., 100.).unwrap()
    );
    let spin_button = gtk::SpinButton::new_with_range(0., 100., 1.).unwrap();
    let mut spinner = gtk::Spinner::new().unwrap();
    let image = gtk::Image::new_from_file("./test/resources/gtk.jpg").unwrap();
    let mut progress_bar = gtk::ProgressBar::new().unwrap();
    let arrow = gtk::Arrow::new(gtk::ArrowType::Right, gtk::ShadowType::EtchedOut).unwrap();
    let calendar = gtk::Calendar::new().unwrap();
    let mut info_bar = gtk::InfoBar::new().unwrap();
    let tmp_button = with_gtk_3_10!(
        gtk::Button::new_from_icon_name("edit-clear", gtk::IconSize::Button).unwrap()
    );

    println!("test");

    with_gtk_3_10! {{
        info_bar.show_close_button(true);
    }}

    /*info_bar.connect(signals::Response::new(|response_id| {
        info_bar.hide()
    }));*/ //TODO: Why does this not work?

    progress_bar.set_fraction(0.7);
    spinner.start();
    with_gtk_3_10! {{
        level_bar.set_value(37.);
    }}
    switch2.set_active(true);
    frame.set_border_width(10);
    _box.set_border_width(5);
    entry.set_placeholder("An Entry with a placeholder !");
    volume_button.set_orientation(gtk::Orientation::Horizontal);
    label.set_justify(gtk::Justification::Left);
    window.set_title("Yeah a beautiful window with rgtk !");
    window.set_window_position(gtk::WindowPosition::Center);
    window.add(&frame);

    Connect::connect(&button, Clicked::new(&mut ||{
        entry.set_text("Clicked!".to_string());

        let dialog = gtk::AboutDialog::new().unwrap();

        let crew = [
            "James T. Kirk",
            "Spock",
            "Leonard McCoy",
        ];

        dialog.set_authors(&crew);
        dialog.set_artists(&crew[1..]);

        println!("Authors: {:?}", dialog.get_authors());
        println!("Artists: {:?}", dialog.get_artists());
        println!("Documenters: {:?}", dialog.get_documenters());

        dialog.run();
        dialog.destroy();
    }));
    Connect::connect(&button_font, Clicked::new(&mut ||{
        let dialog = gtk::FontChooserDialog::new("Font chooser test", None).unwrap();

        dialog.run();
    }));
    Connect::connect(&button_recent, Clicked::new(&mut ||{
        let dialog = gtk::RecentChooserDialog::new("Recent chooser test", None).unwrap();

        dialog.run();
    }));
    Connect::connect(&file_button, Clicked::new(&mut ||{
        //entry.set_text("Clicked!".to_string());
        let dialog = gtk::FileChooserDialog::new("Choose a file", None, gtk::FileChooserAction::Open).unwrap();

        dialog.set_select_multiple(true);

        dialog.run();

        let files = dialog.get_filenames();

        dialog.destroy();

        println!("Files: {:?}", files);
    }));
    Connect::connect(&app_button, Clicked::new(&mut ||{
        //entry.set_text("Clicked!".to_string());
        let dialog = gtk::AppChooserDialog::new_for_content_type(None, gtk::DialogFlags::Modal, "sh").unwrap();

        dialog.run();
    }));

    Connect::connect(&window, KeyPressEvent::new(&mut |key|{
        let keyval = unsafe { (*key).keyval };
        let keystate = unsafe { (*key).state };

        println!("key pressed: {} / {:?}", keyval, keystate);
        println!("text: {}", entry.get_text().unwrap());

        if keystate.intersects(modifier_type::ControlMask) {
            println!("You pressed Ctrl!");
        }
        false
    }));

    Connect::connect(&window, DeleteEvent::new(&mut |_|{
        gtk::main_quit();
        true
    }));

    frame.add(&_box);
    with_gtk_3_10! {{
        button_box.add(&tmp_button)
    }};
    button_box.add(&button);
    button_box.add(&button_font);
    button_box.add(&button_recent);
    button_box.add(&file_button);
    button_box.add(&app_button);
    button_box.add(&font_button);
    button_box.add(&toggle_button);
    button_box.add(&color_button);
    button_box.add(&volume_button);
    v_box.add(&switch);
    with_gtk_3_10! {{
        v_box.add(&menu_button);
    }}
    v_box.add(&switch2);
    v_box.add(&check_button);
    v_box.add(&link_button);
    v_box.add(&spin_button);
    _box.add(&info_bar);
    _box.add(&v_box);
    _box.add(&scale);
    with_gtk_3_10! {{
        _box.add(&level_bar);
    }}
    _box.add(&button_box);
    _box.add(&progress_bar);
    _box.add(&separator);
    _box.add(&label);
    _box.add(&entry);
    _box.add(&separator2);
    with_gtk_3_10! {{
        _box.add(&search_entry);
    }}
    _box.add(&spinner);
    _box.add(&image);
    _box.add(&arrow);
    _box.add(&calendar);
    _box.set_orientation(gtk::Orientation::Vertical);
    // window.set_decorated(false);
    window.set_decorated(true);
    window.show_all();
    gtk::main();
}
<|endoftext|>


<commit_before>extern crate tvdb;

fn main(){
    if std::env::args().count() != 4{
        println!("Usage {} <seriesname> <season number> <episode number>", std::env::args().nth(0).unwrap());
        std::process::exit(1);
    }
    let api = tvdb::Tvdb::new("0629B785CE550C8D".to_owned());
    let sr = api.search(std::env::args().nth(1).unwrap(), "en".to_owned()).ok().unwrap();
    for r in sr.iter(){
        println!("{:?} (id: {})", r.seriesname, r.seriesid);
    }
}
<commit_msg>tvdb-lookup example gets episode name<commit_after>extern crate tvdb;

fn main(){
    if std::env::args().count() != 4{
        println!("Usage {} <seriesname> <season number> <episode number>", std::env::args().nth(0).unwrap());
        std::process::exit(1);
    }
    let api = tvdb::Tvdb::new("0629B785CE550C8D".to_owned());
    let sr = api.search(std::env::args().nth(1).unwrap(), "en".to_owned()).ok().unwrap();
    for r in sr.iter(){
        println!("{:?} (id: {})", r.seriesname, r.seriesid);
        println!("{:?}", api.episode(sr[0].clone(), 1, 2));
    }
}
<|endoftext|>


<commit_before>use rustc_data_structures::fx::FxHashMap;
use std::cell::RefCell;
use std::hash::Hash;
use std::marker::PhantomData;
use crate::util::common::MemoizationMap;

use super::{DepKind, DepNodeIndex, DepGraph};

/// A DepTrackingMap offers a subset of the `Map` API and ensures that
/// we make calls to `read` and `write` as appropriate. We key the
/// maps with a unique type for brevity.
pub struct DepTrackingMap<M: DepTrackingMapConfig> {
    phantom: PhantomData<M>,
    graph: DepGraph,
    map: FxHashMap<M::Key, (M::Value, DepNodeIndex)>,
}

pub trait DepTrackingMapConfig {
    type Key: Eq + Hash + Clone;
    type Value: Clone;
    fn to_dep_kind() -> DepKind;
}

impl<M: DepTrackingMapConfig> DepTrackingMap<M> {
    pub fn new(graph: DepGraph) -> DepTrackingMap<M> {
        DepTrackingMap {
            phantom: PhantomData,
            graph,
            map: Default::default(),
        }
    }
}

impl<M: DepTrackingMapConfig> MemoizationMap for RefCell<DepTrackingMap<M>> {
    type Key = M::Key;
    type Value = M::Value;

    /// Memoizes an entry in the dep-tracking-map. If the entry is not
    /// already present, then `op` will be executed to compute its value.
    /// The resulting dependency graph looks like this:
    ///
    ///     [op] -> Map(key) -> CurrentTask
    ///
    /// Here, `[op]` represents whatever nodes `op` reads in the
    /// course of execution; `Map(key)` represents the node for this
    /// map, and `CurrentTask` represents the current task when
    /// `memoize` is invoked.
    ///
    /// **Important:** when `op` is invoked, the current task will be
    /// switched to `Map(key)`. Therefore, if `op` makes use of any
    /// HIR nodes or shared state accessed through its closure
    /// environment, it must explicitly register a read of that
    /// state. As an example, see `type_of_item` in `collect`,
    /// which looks something like this:
    ///
    /// ```
    /// fn type_of_item(..., item: &hir::Item) -> Ty<'tcx> {
    ///     let item_def_id = ccx.tcx.hir().local_def_id_from_node_id(it.id);
    ///     ccx.tcx.item_types.memoized(item_def_id, || {
    ///         ccx.tcx.dep_graph.read(DepNode::Hir(item_def_id)); // (*)
    ///         compute_type_of_item(ccx, item)
    ///     });
    /// }
    /// ```
    ///
    /// The key is the line marked `(*)`: the closure implicitly
    /// accesses the body of the item `item`, so we register a read
    /// from `Hir(item_def_id)`.
    fn memoize<OP>(&self, key: M::Key, op: OP) -> M::Value
        where OP: FnOnce() -> M::Value
    {
        let graph;
        {
            let this = self.borrow();
            if let Some(&(ref result, dep_node)) = this.map.get(&key) {
                this.graph.read_index(dep_node);
                return result.clone();
            }
            graph = this.graph.clone();
        }

        let (result, dep_node) = graph.with_anon_task(M::to_dep_kind(), op);
        self.borrow_mut().map.insert(key, (result.clone(), dep_node));
        graph.read_index(dep_node);
        result
    }
}
<commit_msg>fix a dep_graph doc regarding type_of_item<commit_after>use rustc_data_structures::fx::FxHashMap;
use std::cell::RefCell;
use std::hash::Hash;
use std::marker::PhantomData;
use crate::util::common::MemoizationMap;

use super::{DepKind, DepNodeIndex, DepGraph};

/// A DepTrackingMap offers a subset of the `Map` API and ensures that
/// we make calls to `read` and `write` as appropriate. We key the
/// maps with a unique type for brevity.
pub struct DepTrackingMap<M: DepTrackingMapConfig> {
    phantom: PhantomData<M>,
    graph: DepGraph,
    map: FxHashMap<M::Key, (M::Value, DepNodeIndex)>,
}

pub trait DepTrackingMapConfig {
    type Key: Eq + Hash + Clone;
    type Value: Clone;
    fn to_dep_kind() -> DepKind;
}

impl<M: DepTrackingMapConfig> DepTrackingMap<M> {
    pub fn new(graph: DepGraph) -> DepTrackingMap<M> {
        DepTrackingMap {
            phantom: PhantomData,
            graph,
            map: Default::default(),
        }
    }
}

impl<M: DepTrackingMapConfig> MemoizationMap for RefCell<DepTrackingMap<M>> {
    type Key = M::Key;
    type Value = M::Value;

    /// Memoizes an entry in the dep-tracking-map. If the entry is not
    /// already present, then `op` will be executed to compute its value.
    /// The resulting dependency graph looks like this:
    ///
    ///     [op] -> Map(key) -> CurrentTask
    ///
    /// Here, `[op]` represents whatever nodes `op` reads in the
    /// course of execution; `Map(key)` represents the node for this
    /// map, and `CurrentTask` represents the current task when
    /// `memoize` is invoked.
    ///
    /// **Important:** when `op` is invoked, the current task will be
    /// switched to `Map(key)`. Therefore, if `op` makes use of any
    /// HIR nodes or shared state accessed through its closure
    /// environment, it must explicitly register a read of that
    /// state. As an example, see `type_of_item` in `collect`,
    /// which looks something like this:
    ///
    /// ```
    /// fn type_of_item(..., item: &hir::Item) -> Ty<'tcx> {
    ///     let item_def_id = ccx.tcx.hir().local_def_id(it.hir_id);
    ///     ccx.tcx.item_types.memoized(item_def_id, || {
    ///         ccx.tcx.dep_graph.read(DepNode::Hir(item_def_id)); // (*)
    ///         compute_type_of_item(ccx, item)
    ///     });
    /// }
    /// ```
    ///
    /// The key is the line marked `(*)`: the closure implicitly
    /// accesses the body of the item `item`, so we register a read
    /// from `Hir(item_def_id)`.
    fn memoize<OP>(&self, key: M::Key, op: OP) -> M::Value
        where OP: FnOnce() -> M::Value
    {
        let graph;
        {
            let this = self.borrow();
            if let Some(&(ref result, dep_node)) = this.map.get(&key) {
                this.graph.read_index(dep_node);
                return result.clone();
            }
            graph = this.graph.clone();
        }

        let (result, dep_node) = graph.with_anon_task(M::to_dep_kind(), op);
        self.borrow_mut().map.insert(key, (result.clone(), dep_node));
        graph.read_index(dep_node);
        result
    }
}
<|endoftext|>


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

#[macro_escape];

use std::fmt;

macro_rules! uverrln (
    ($($arg:tt)*) => ( {
        format_args!(::macros::dumb_println, $($arg)*)
    } )
)

// Some basic logging. Enabled by passing `--cfg uvdebug` to the libstd build.
macro_rules! uvdebug (
    ($($arg:tt)*) => ( {
        if cfg!(uvdebug) {
            uverrln!($($arg)*)
        }
    })
)

pub fn dumb_println(args: &fmt::Arguments) {
    use std::io;
    use std::libc;

    struct Stderr;
    impl io::Writer for Stderr {
        fn write(&mut self, data: &[u8]) {
            unsafe {
                libc::write(libc::STDERR_FILENO,
                            data.as_ptr() as *libc::c_void,
                            data.len() as libc::size_t);
            }
        }
    }
    let mut w = Stderr;
    fmt::writeln(&mut w as &mut io::Writer, args);
}
<commit_msg>rustuv: Remove io_error usage<commit_after>// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

#[macro_escape];

use std::fmt;

macro_rules! uverrln (
    ($($arg:tt)*) => ( {
        format_args!(::macros::dumb_println, $($arg)*)
    } )
)

// Some basic logging. Enabled by passing `--cfg uvdebug` to the libstd build.
macro_rules! uvdebug (
    ($($arg:tt)*) => ( {
        if cfg!(uvdebug) {
            uverrln!($($arg)*)
        }
    })
)

pub fn dumb_println(args: &fmt::Arguments) {
    use std::io;
    use std::libc;

    struct Stderr;
    impl io::Writer for Stderr {
        fn write(&mut self, data: &[u8]) -> io::IoResult<()> {
            unsafe {
                libc::write(libc::STDERR_FILENO,
                            data.as_ptr() as *libc::c_void,
                            data.len() as libc::size_t);
            }
            Ok(()) // just ignore the errors
        }
    }
    let mut w = Stderr;
    let _ = fmt::writeln(&mut w as &mut io::Writer, args);
}
<|endoftext|>


<commit_before>use hypercall::hypercall2;
use hypercall::HypercallKind;

use defs::Ulong;

#[allow(dead_code)]
enum SchedOp {
    Yield = 0,
    Block = 1,
    Shutdown = 2,
    Poll = 3,
    RemoteShutdown = 4,
    ShutdownCode = 5,
    Watchdog = 6,
}

#[allow(dead_code)]
enum ShutdownReason {
    PowerOff = 0,
    Reboot = 1,
    Suspend = 2,
    Crash = 3,
    Watchdog = 4,
}

#[repr(C)]
struct SchedShutdown {
    reason: u32,
}

#[inline]
fn sched_op(op: SchedOp, sched: Ulong) -> i32 {
    unsafe {
        hypercall2(HypercallKind::SchedOp, op as Ulong, sched) as i32
    }
}

pub fn yield_cpu() -> i32 {
    sched_op(SchedOp::Yield, 0)
}

fn shutdown(reason: ShutdownReason) -> i32 {
    let r = SchedShutdown {
        reason: reason as u32,
    };

    sched_op(SchedOp::Shutdown, &r as *const SchedShutdown as Ulong)
}

fn shutdown_code(status: Ulong) -> i32 {
    sched_op(SchedOp::ShutdownCode, status)
}

pub fn crash() -> i32 {
    shutdown(ShutdownReason::Crash)
}

pub fn poweroff(status: Ulong) -> i32 {
    let ret: i32 = shutdown_code(status);

    if ret < 0 {
        return ret
    }

    shutdown(ShutdownReason::PowerOff)
}

<commit_msg>libxen: Add sched::block()<commit_after>use hypercall::hypercall2;
use hypercall::HypercallKind;

use defs::Ulong;

#[allow(dead_code)]
enum SchedOp {
    Yield = 0,
    Block = 1,
    Shutdown = 2,
    Poll = 3,
    RemoteShutdown = 4,
    ShutdownCode = 5,
    Watchdog = 6,
}

#[allow(dead_code)]
enum ShutdownReason {
    PowerOff = 0,
    Reboot = 1,
    Suspend = 2,
    Crash = 3,
    Watchdog = 4,
}

#[repr(C)]
struct SchedShutdown {
    reason: u32,
}

#[inline]
fn sched_op(op: SchedOp, sched: Ulong) -> i32 {
    unsafe {
        hypercall2(HypercallKind::SchedOp, op as Ulong, sched) as i32
    }
}

pub fn yield_cpu() -> i32 {
    sched_op(SchedOp::Yield, 0)
}

pub fn block() -> i32 {
    sched_op(SchedOp::Block, 0)
}

fn shutdown(reason: ShutdownReason) -> i32 {
    let r = SchedShutdown {
        reason: reason as u32,
    };

    sched_op(SchedOp::Shutdown, &r as *const SchedShutdown as Ulong)
}

fn shutdown_code(status: Ulong) -> i32 {
    sched_op(SchedOp::ShutdownCode, status)
}

pub fn crash() -> i32 {
    shutdown(ShutdownReason::Crash)
}

pub fn poweroff(status: Ulong) -> i32 {
    let ret: i32 = shutdown_code(status);

    if ret < 0 {
        return ret
    }

    shutdown(ShutdownReason::PowerOff)
}

<|endoftext|>


<commit_before>use std::mem;

// This function borrows a slice
fn analyze_slice(slice: &[int]) {
    println!("first element of the slice: {}", slice[0]);
    println!("the slice has {} elements", slice.len());
}

fn main() {
    // Fixed-size array (type signature is superfluous)
    let xs: [int, ..5] = [1, 2, 3, 4, 5];

    // Indexing starts at 0
    println!("first element of the array: {}", xs[0]);
    println!("second element of the array: {}", xs[1]);

    // `len` returns the size of the array
    println!("array size: {}", xs.len());

    // Arrays are stack allocated
    println!("array occupies {} bytes", mem::size_of_val(&xs));

    // Arrays can be automatically borrowed as slices
    println!("borrow the whole array as a slice");
    analyze_slice(xs);

    // Slices can point to a section of an array
    println!("borrow a section of the array as a slice");
    analyze_slice(xs.slice(1, 4));

    // Out of bound indexing yields a task failure
    println!("{}", xs[5]);
}
<commit_msg>add example of initializing an array without literal<commit_after>use std::mem;

// This function borrows a slice
fn analyze_slice(slice: &[int]) {
    println!("first element of the slice: {}", slice[0]);
    println!("the slice has {} elements", slice.len());
}

fn main() {
    // Fixed-size array (type signature is superfluous)
    let xs: [int, ..5] = [1, 2, 3, 4, 5];

    // All elements can be initialized to the same value
    let ys: [int, ..500] = [0, ..500];

    // Indexing starts at 0
    println!("first element of the array: {}", xs[0]);
    println!("second element of the array: {}", xs[1]);

    // `len` returns the size of the array
    println!("array size: {}", xs.len());

    // Arrays are stack allocated
    println!("array occupies {} bytes", mem::size_of_val(&xs));

    // Arrays can be automatically borrowed as slices
    println!("borrow the whole array as a slice");
    analyze_slice(xs);

    // Slices can point to a section of an array
    println!("borrow a section of the array as a slice");
    analyze_slice(ys.slice(1, 4));

    // Out of bound indexing yields a task failure
    println!("{}", xs[5]);
}
<|endoftext|>


<commit_before>extern crate libcapstone_sys;

use libcapstone_sys::*;

fn main() {
    let mut engine: csh;
    cs_open(CS_ARCH_X86, CS_MODE_64, &mut engine);
}<commit_msg>Remove example file<commit_after><|endoftext|>


<commit_before>// Copyright 2016 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// See the License for the specific language governing permissions and
// limitations under the License.

use super::util::*;
use super::cluster::{Cluster, Simulator};
use super::transport_simulate::DropSnapshot;
use super::node::new_node_cluster;
use super::server::new_server_cluster;
use std::time::Duration;

fn test_transfer_leader<T: Simulator>(cluster: &mut Cluster<T>) {
    cluster.run();

    // transfer leader to (2, 2)
    cluster.must_transfer_leader(1, new_peer(2, 2));
    // wait for leader transfer finish
    let (k1, v1) = (b"k1", b"v1");
    cluster.must_put(k1, v1);
    must_get_equal(&cluster.engines[&2], k1, v1);
    // check it
    assert_eq!(cluster.leader_of_region(1), Some(new_peer(2, 2)));

    // transfer leader to (3, 3)
    cluster.must_transfer_leader(1, new_peer(3, 3));
    let (k2, v2) = (b"k2", b"v2");
    cluster.must_put(k2, v2);
    must_get_equal(&cluster.engines[&3], k2, v2);
    assert_eq!(cluster.leader_of_region(1), Some(new_peer(3, 3)));

    let mut region = cluster.get_region(b"k3");
    let mut req = new_request(region.get_id(),
                              region.take_region_epoch(),
                              vec![new_put_cmd(b"k3", b"v3")]);
    req.mut_header().set_peer(new_peer(3, 3));
    // transfer leader to (4, 4)
    cluster.must_transfer_leader(1, new_peer(4, 4));
    // send request to old leader (3, 3) directly and verify it fails
    let resp = cluster.call_command(req, Duration::from_secs(3)).unwrap();
    assert!(resp.get_header().get_error().has_not_leader());
}

#[test]
fn test_server_transfer_leader() {
    let mut cluster = new_node_cluster(0, 5);
    test_transfer_leader(&mut cluster);
}

#[test]
fn test_node_transfer_leader() {
    let mut cluster = new_server_cluster(0, 5);
    test_transfer_leader(&mut cluster);
}

fn test_pd_transfer_leader<T: Simulator>(cluster: &mut Cluster<T>) {
    let pd_client = cluster.pd_client.clone();
    pd_client.disable_default_rule();

    cluster.run();

    cluster.must_put(b"k", b"v");

    for i in 1..4 {
        let id = i as u64;
        // select a new leader to transfer
        pd_client.set_rule(box move |_, peer| {
            if peer.get_id() == id {
                return None;
            }
            new_pd_transfer_leader(new_peer(id, id))
        });

        for _ in 0..100 {
            // reset leader and wait transfer successfully.
            cluster.reset_leader_of_region(1);

            sleep_ms(20);

            if let Some(leader) = cluster.leader_of_region(1) {
                if leader.get_id() == id {
                    break;
                }
            }
        }

        assert_eq!(cluster.leader_of_region(1), Some(new_peer(id, id)));

        // call command on this leader directly, must successfully.
        let mut region = cluster.get_region(b"");
        let mut req = new_request(region.get_id(),
                                  region.take_region_epoch(),
                                  vec![new_get_cmd(b"k")]);
        req.mut_header().set_peer(new_peer(id, id));
        let resp = cluster.call_command(req, Duration::from_secs(3)).unwrap();
        assert!(!resp.get_header().has_error());
        assert_eq!(resp.get_responses()[0].get_get().get_value(), b"v");
    }
}

#[test]
fn test_server_pd_transfer_leader() {
    let mut cluster = new_node_cluster(0, 3);
    test_pd_transfer_leader(&mut cluster);
}

#[test]
fn test_node_pd_transfer_leader() {
    let mut cluster = new_server_cluster(0, 3);
    test_pd_transfer_leader(&mut cluster);
}

fn test_transfer_leader_during_snapshot<T: Simulator>(cluster: &mut Cluster<T>) {
    let pd_client = cluster.pd_client.clone();
    // Disable default max peer count check.
    pd_client.disable_default_rule();
    cluster.cfg.store_cfg.raft_log_gc_tick_interval = 20;
    cluster.cfg.store_cfg.raft_log_gc_limit = 2;

    let r1 = cluster.run_conf_change();
    pd_client.must_add_peer(r1, new_peer(2, 2));

    for i in 0..1024 {
        let key = format!("{:01024}", i);
        let value = format!("{:01024}", i);
        cluster.must_put(key.as_bytes(), value.as_bytes());
    }

    // hook transport and drop all snapshot packet, so follower's status
    // will stay at snapshot.
    cluster.add_filter(DropSnapshot);
    pd_client.must_add_peer(r1, new_peer(3, 3));
    // a just added peer needs wait a couple of ticks, it'll communicate with leader
    // before getting snapshot
    sleep_ms(1000);

    cluster.transfer_leader(r1, new_peer(2, 2));
    cluster.clear_filters();

    sleep_ms(1000);
    cluster.must_put(b"k1", b"v1");
    let leader = cluster.leader_of_region(r1).unwrap();
    must_get_equal(&cluster.engines[&2], b"k1", b"v1");
    assert_eq!(leader, new_peer(1, 1));
}

#[test]
fn test_server_transfer_leader_during_snapshot() {
    let mut cluster = new_node_cluster(0, 3);
    test_transfer_leader_during_snapshot(&mut cluster);
}

#[test]
fn test_node_transfer_leader_during_snapshot() {
    let mut cluster = new_server_cluster(0, 3);
    test_transfer_leader_during_snapshot(&mut cluster);
}
<commit_msg>tests: fix transfer leader fail (#765)<commit_after>// Copyright 2016 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// See the License for the specific language governing permissions and
// limitations under the License.

use super::util::*;
use super::cluster::{Cluster, Simulator};
use super::transport_simulate::DropSnapshot;
use super::node::new_node_cluster;
use super::server::new_server_cluster;
use std::time::Duration;

fn test_transfer_leader<T: Simulator>(cluster: &mut Cluster<T>) {
    cluster.run();

    // transfer leader to (2, 2)
    cluster.must_transfer_leader(1, new_peer(2, 2));

    // transfer leader to (3, 3)
    cluster.must_transfer_leader(1, new_peer(3, 3));

    let mut region = cluster.get_region(b"k3");
    let mut req = new_request(region.get_id(),
                              region.take_region_epoch(),
                              vec![new_put_cmd(b"k3", b"v3")]);
    req.mut_header().set_peer(new_peer(3, 3));
    // transfer leader to (4, 4)
    cluster.must_transfer_leader(1, new_peer(4, 4));
    // send request to old leader (3, 3) directly and verify it fails
    let resp = cluster.call_command(req, Duration::from_secs(3)).unwrap();
    assert!(resp.get_header().get_error().has_not_leader());
}

#[test]
fn test_server_transfer_leader() {
    let mut cluster = new_node_cluster(0, 5);
    test_transfer_leader(&mut cluster);
}

#[test]
fn test_node_transfer_leader() {
    let mut cluster = new_server_cluster(0, 5);
    test_transfer_leader(&mut cluster);
}

fn test_pd_transfer_leader<T: Simulator>(cluster: &mut Cluster<T>) {
    let pd_client = cluster.pd_client.clone();
    pd_client.disable_default_rule();

    cluster.run();

    cluster.must_put(b"k", b"v");

    for i in 1..4 {
        let id = i as u64;
        // select a new leader to transfer
        pd_client.set_rule(box move |_, peer| {
            if peer.get_id() == id {
                return None;
            }
            new_pd_transfer_leader(new_peer(id, id))
        });

        for _ in 0..100 {
            // reset leader and wait transfer successfully.
            cluster.reset_leader_of_region(1);

            sleep_ms(20);

            if let Some(leader) = cluster.leader_of_region(1) {
                if leader.get_id() == id {
                    break;
                }
            }
        }

        assert_eq!(cluster.leader_of_region(1), Some(new_peer(id, id)));

        // call command on this leader directly, must successfully.
        let mut region = cluster.get_region(b"");
        let mut req = new_request(region.get_id(),
                                  region.take_region_epoch(),
                                  vec![new_get_cmd(b"k")]);
        req.mut_header().set_peer(new_peer(id, id));
        let resp = cluster.call_command(req, Duration::from_secs(3)).unwrap();
        assert!(!resp.get_header().has_error());
        assert_eq!(resp.get_responses()[0].get_get().get_value(), b"v");
    }
}

#[test]
fn test_server_pd_transfer_leader() {
    let mut cluster = new_node_cluster(0, 3);
    test_pd_transfer_leader(&mut cluster);
}

#[test]
fn test_node_pd_transfer_leader() {
    let mut cluster = new_server_cluster(0, 3);
    test_pd_transfer_leader(&mut cluster);
}

fn test_transfer_leader_during_snapshot<T: Simulator>(cluster: &mut Cluster<T>) {
    let pd_client = cluster.pd_client.clone();
    // Disable default max peer count check.
    pd_client.disable_default_rule();
    cluster.cfg.store_cfg.raft_log_gc_tick_interval = 20;
    cluster.cfg.store_cfg.raft_log_gc_limit = 2;

    let r1 = cluster.run_conf_change();
    pd_client.must_add_peer(r1, new_peer(2, 2));

    for i in 0..1024 {
        let key = format!("{:01024}", i);
        let value = format!("{:01024}", i);
        cluster.must_put(key.as_bytes(), value.as_bytes());
    }

    cluster.must_transfer_leader(r1, new_peer(1, 1));

    // hook transport and drop all snapshot packet, so follower's status
    // will stay at snapshot.
    cluster.add_filter(DropSnapshot);
    pd_client.must_add_peer(r1, new_peer(3, 3));
    // a just added peer needs wait a couple of ticks, it'll communicate with leader
    // before getting snapshot
    sleep_ms(1000);

    cluster.transfer_leader(r1, new_peer(2, 2));
    cluster.clear_filters();

    sleep_ms(1000);
    cluster.must_put(b"k1", b"v1");
    let leader = cluster.leader_of_region(r1).unwrap();
    must_get_equal(&cluster.engines[&2], b"k1", b"v1");
    assert_eq!(leader, new_peer(1, 1));
}

#[test]
fn test_server_transfer_leader_during_snapshot() {
    let mut cluster = new_node_cluster(0, 3);
    test_transfer_leader_during_snapshot(&mut cluster);
}

#[test]
fn test_node_transfer_leader_during_snapshot() {
    let mut cluster = new_server_cluster(0, 3);
    test_transfer_leader_during_snapshot(&mut cluster);
}
<|endoftext|>


<commit_before>#![feature(rustc_attrs)]
#![deny(const_err)]

fn black_box<T>(_: T) {
    unimplemented!()
}

fn main() {
    let b = 200u8 + 200u8 + 200u8;
    //~^ ERROR overflow
    let c = 200u8 * 4;
    //~^ ERROR overflow
    let d = 42u8 - (42u8 + 1);
    //~^ ERROR overflow
    let _e = [5u8][1];
    //~^ ERROR panic
    black_box(b);
    black_box(c);
    black_box(d);
}
<commit_msg>remove no-longer-needed test<commit_after><|endoftext|>


<commit_before>// Copyright (c) <2015> <lummax>
// Licensed under MIT (http://opensource.org/licenses/MIT)

extern crate wayland_client;
use wayland_client::client::{FromPrimitive, Display,
                             Registry, RegistryEventHandler,
                             Seat, SeatEventHandler, SeatCapability,
                             Shm, ShmEventHandler, ShmFormat,
                             Output, OutputEventHandler, OutputSubpixel,
                             OutputTransform, OutputMode};

#[derive(Debug)]
struct MyRegistry {
    registry: Registry,
    seat: Option<MySeat>,
    shm: Option<MyShm>,
    output: Option<MyOutput>,
    pub roundtrip: bool,
}

impl MyRegistry {
    fn new(registry: Registry) -> MyRegistry {
        return MyRegistry {
            registry: registry,
            seat: None,
            shm: None,
            output: None,
            roundtrip: true,
        };
    }
}

impl RegistryEventHandler for MyRegistry {
    fn get_registry(&mut self) -> &mut Registry {
        return &mut self.registry;
    }

    fn on_global(&mut self, name: u32, interface: String, version: u32) {
        println!("interface: '{}', version: {}, name: {}", interface, version, name);
        if interface == "wl_seat" {
            self.roundtrip = true;
            let mut seat = MySeat::new(self.registry.bind(name, version).unwrap());
            seat.connect_dispatcher();
            self.seat = Some(seat);
        } else if interface == "wl_shm" {
            self.roundtrip = true;
            let mut shm = MyShm::new(self.registry.bind(name, version).unwrap());
            shm.connect_dispatcher();
            self.shm = Some(shm);
        } else if interface == "wl_output" {
            self.roundtrip = true;
            let mut output = MyOutput::new(self.registry.bind(name, version).unwrap());
            output.connect_dispatcher();
            self.output = Some(output);
        }
    }

    fn on_global_remove(&mut self, name: u32) {
        println!("on_global_remove({})", name);
    }
}

#[derive(Debug)]
struct MySeat {
    seat: Seat,
}

impl MySeat {
    fn new(seat: Seat) -> MySeat {
        return MySeat { seat: seat };
    }
}

impl SeatEventHandler for MySeat {
    fn get_seat(&mut self) -> &mut Seat {
        return &mut self.seat;
    }

    fn on_capabilities(&mut self, capabilities: u32) {
        println!("on_capabilities({})", capabilities);
    }

    fn on_name(&mut self, name: String) {
        println!("on_name({})", name);
    }
}

#[derive(Debug)]
struct MyShm {
    shm: Shm,
}

impl MyShm {
    fn new(shm: Shm) -> MyShm {
        return MyShm { shm: shm };
    }
}

impl ShmEventHandler for MyShm {
    fn get_shm(&mut self) -> &mut Shm {
        return &mut self.shm;
    }

    fn on_format(&mut self, format: u32) {
        println!("on_format({:?})", ShmFormat::from_u32(format).unwrap());
    }
}

#[derive(Debug)]
struct MyOutput {
    output: Output,
}

impl MyOutput {
    fn new(output: Output) -> MyOutput {
        return MyOutput { output: output };
    }
}

impl OutputEventHandler for MyOutput {
    fn get_output(&mut self) -> &mut Output {
        return &mut self.output;
    }

    fn on_geometry(&mut self, x: i32, y: i32, physical_width: i32,
                   physical_height: i32, subpixel: i32, make: String, model:
                   String, transform: i32) {
        println!("on_geometry({}, {}, {}, {}, {:?}, {}, {}, {:?})", x, y,
            physical_width, physical_height,
            OutputSubpixel::from_u32(subpixel as u32).unwrap(), make, model,
            OutputTransform::from_u32(transform as u32).unwrap());
    }

    fn on_mode(&mut self, flags: u32, width: i32, height: i32, refresh: i32) {
        println!("on_mode({}, {}, {}, {})", flags, width, height, refresh);
    }

    fn on_done(&mut self) {
        println!("on_done()");
    }

    fn on_scale(&mut self, factor: i32) {
        println!("on_scale({})", factor);
    }
}

fn main() {
    let mut display = Display::connect(None).unwrap();
    let mut registry = MyRegistry::new(display.get_registry().unwrap());
    registry.connect_dispatcher();

    while registry.roundtrip {
        registry.roundtrip = false;
        display.roundtrip();
    }
}
<commit_msg>weston-info: use single struct<commit_after>// Copyright (c) <2015> <lummax>
// Licensed under MIT (http://opensource.org/licenses/MIT)

extern crate wayland_client;
use wayland_client::client::{FromPrimitive, Display,
                             Registry, RegistryEventHandler,
                             Seat, SeatEventHandler, SeatCapability,
                             Shm, ShmEventHandler, ShmFormat,
                             Output, OutputEventHandler, OutputSubpixel,
                             OutputTransform, OutputMode};

#[derive(Debug)]
struct Info {
    registry: Registry,
    seat: Option<Seat>,
    shm: Option<Shm>,
    output: Option<Output>,
    pub roundtrip: bool,
}

impl Info {
    fn new(registry: Registry) -> Info {
        return Info {
            registry: registry,
            seat: None,
            shm: None,
            output: None,
            roundtrip: true,
        };
    }
}

impl RegistryEventHandler for Info {
    fn get_registry(&mut self) -> &mut Registry {
        return &mut self.registry;
    }

    fn on_global(&mut self, name: u32, interface: String, version: u32) {
        println!("interface: '{}', version: {}, name: {}", interface, version, name);
        if interface == "wl_seat" {
            self.roundtrip = true;
            self.seat = self.registry.bind(name, version).ok();
            SeatEventHandler::connect_dispatcher(self);
        } else if interface == "wl_shm" {
            self.roundtrip = true;
            self.shm = self.registry.bind(name, version).ok();
            ShmEventHandler::connect_dispatcher(self);
        } else if interface == "wl_output" {
            self.roundtrip = true;
            self.output = self.registry.bind(name, version).ok();
            OutputEventHandler::connect_dispatcher(self);
        }
    }

    fn on_global_remove(&mut self, name: u32) {
        println!("on_global_remove({})", name);
    }
}

impl SeatEventHandler for Info {
    fn get_seat(&mut self) -> &mut Seat {
        return self.seat.as_mut().unwrap();
    }

    fn on_capabilities(&mut self, capabilities: u32) {
        println!("on_capabilities({})", capabilities);
    }

    fn on_name(&mut self, name: String) {
        println!("on_name({})", name);
    }
}

impl ShmEventHandler for Info {
    fn get_shm(&mut self) -> &mut Shm {
        return self.shm.as_mut().unwrap();
    }

    fn on_format(&mut self, format: u32) {
        println!("on_format({:?})", ShmFormat::from_u32(format).unwrap());
    }
}

impl OutputEventHandler for Info {
    fn get_output(&mut self) -> &mut Output {
        return self.output.as_mut().unwrap();
    }

    fn on_geometry(&mut self, x: i32, y: i32, physical_width: i32,
                   physical_height: i32, subpixel: i32, make: String, model:
                   String, transform: i32) {
        println!("on_geometry({}, {}, {}, {}, {:?}, {}, {}, {:?})", x, y,
            physical_width, physical_height,
            OutputSubpixel::from_u32(subpixel as u32).unwrap(), make, model,
            OutputTransform::from_u32(transform as u32).unwrap());
    }

    fn on_mode(&mut self, flags: u32, width: i32, height: i32, refresh: i32) {
        println!("on_mode({}, {}, {}, {})", flags, width, height, refresh);
    }

    fn on_done(&mut self) {
        println!("on_done()");
    }

    fn on_scale(&mut self, factor: i32) {
        println!("on_scale({})", factor);
    }
}

fn main() {
    let mut display = Display::connect(None).unwrap();
    let mut info = Info::new(display.get_registry().unwrap());
    RegistryEventHandler::connect_dispatcher(&mut info);

    while info.roundtrip {
        info.roundtrip = false;
        display.roundtrip();
    }
}
<|endoftext|>