<commit_before>use runtime::Runtime;
use storage::backend::{StorageBackendError, StorageBackend};

use module::Module;
use module::ModuleError;
use module::CommandResult;
use module::CommandEnv;

use module::bm::header::build_header;
use module::bm::header::get_tags_from_header;
use storage::json::parser::JsonHeaderParser;
use storage::parser::{Parser, FileHeaderParser};
use storage::file::File;
use ui::file::{FilePrinter, TablePrinter};
use std::vec::IntoIter;

use clap::ArgMatches;
use regex::Regex;

pub fn add_command(module: &Module, env: CommandEnv) -> CommandResult {
    use url::Url;

    let url = env.matches.value_of("url").unwrap();

    if let Err(e) = Url::parse(url) {
        info!("Not an URL: '{}'", url);
        info!("  this will turn into an hard error before 0.1.0");
        debug!("URL parsing error: {:?}", e);
    }

    let tags = get_tags(env.rt, env.matches);
    info!("Adding url '{}' with tags '{:?}'", url, tags);

    let header  = build_header(&String::from(url), &tags);
    let file    = File::new_with_header(module, header);
    let parser  = Parser::new(JsonHeaderParser::new(None));
    let putres  = env.bk.put_file(file, &parser);

    putres.map_err(|sberr| {
        let mut err = ModuleError::new("Storage Backend Error");
        err.caused_by = Some(Box::new(sberr));
        err
    })
}

pub fn list_command(module: &Module, env: CommandEnv) -> CommandResult {
    let printer = TablePrinter::new(env.rt.is_verbose(), env.rt.is_debugging());
    let files   = get_filtered_files_from_backend(module, &env);

    debug!("Printing files now");
    files.map(|f| printer.print_files(f));

    Ok(())
}

pub fn remove_command(module: &Module, env: CommandEnv) -> CommandResult {
    let checked : bool = run_removal_checking(&env);
    debug!("Checked mode: {}", checked);
    if let Some(id) = get_id(env.rt, env.matches) {
        debug!("Remove by id: {}", id);

        let parser = Parser::new(JsonHeaderParser::new(None));
        let file   = env.bk.get_file_by_id(module, &id.into(), &parser).unwrap();
        debug!("Remove file  : {:?}", file);

        if let Err(e) = env.bk.remove_file(module, file, checked) {
            debug!("Remove failed");
            let mut err = ModuleError::new("Removing file failed");
            err.caused_by = Some(Box::new(e));
            Err(err)
        } else {
            debug!("Remove worked");
            Ok(())
        }
    } else {
        debug!("Remove more than one file");

        get_filtered_files_from_backend(module, &env).and_then(|files| {
            let nfiles = files.len();
            info!("Removing {} Files", nfiles);

            let errs = files.map(|file| {
                    debug!("Remove file: {:?}", file);
                    env.bk.remove_file(module, file, checked)
                })
                .filter(|e| e.is_err())
                .map(|e| {
                    let err = e.err().unwrap();
                    warn!("Error occured in Filesystem operation: {}", err);
                    err
                })
                .collect::<Vec<StorageBackendError>>();

            let nerrs = errs.len();

            if nerrs != 0 {
                warn!("{} Errors occured while removing {} files", nerrs, nfiles);
                let moderr = ModuleError::new("File removal failed");

                // TODO : Collect StorageBackendErrors

                Err(moderr)
            } else {
                Ok(())
            }
        })
    }
}

/*
 *
 * Private helpers
 *
 */

fn get_filtered_files_from_backend<'a>(module: &'a Module,
                                       env: &CommandEnv)
    -> Result<IntoIter<File<'a>>, ModuleError>
{
    let parser = Parser::new(JsonHeaderParser::new(None));
    let tags = get_tags(env.rt, env.matches);
    debug!("Tags: {:?}", tags);
    env.bk.iter_files(module, &parser)
        .map(|files| {
            let f = files.filter(|file| {
                debug!("Backend returns file: {:?}", file);
                if tags.len() != 0 {
                    debug!("Checking tags of: {:?}", file.id());
                    get_tags_from_header(&file.header()).iter()
                        .any(|t| tags.contains(t))
                } else {
                    true
                }
            }).filter(|file| {
                debug!("Checking matches of: {:?}", file.id());
                get_matcher(env.rt, env.matches)
                    .and_then(|r| Some(file.matches_with(&r)))
                    .unwrap_or(true)
            }).collect::<Vec<File>>();
            f.into_iter()
        }).map_err(|e| {
            debug!("Error from Backend: {:?}", e);
            let mut merr = ModuleError::new("Could not filter files");
            merr.caused_by = Some(Box::new(e));
            merr
        })
}

fn get_tags<'a>(rt: &Runtime, sub: &ArgMatches<'a, 'a>) -> Vec<String> {
    debug!("Fetching tags from commandline");
    sub.value_of("tags").and_then(|tags|
                                  Some(tags.split(",")
                                       .into_iter()
                                       .map(|s| s.to_string())
                                       .filter(|e|
                                            if e.contains(" ") {
                                                warn!("Tag contains spaces: '{}'", e);
                                                false
                                            } else {
                                                true
                                            }).collect()
                                      )
                                 ).or(Some(vec![])).unwrap()

}

fn get_matcher<'a>(rt: &Runtime, sub: &ArgMatches<'a, 'a>) -> Option<Regex> {
    debug!("Fetching matcher from commandline");
    if let Some(s) = sub.value_of("match") {
        if let Ok(r) = Regex::new(s) {
            return Some(r)
        } else {
            error!("Regex error, continuing without regex");
        }
    }
    None

}

fn get_id<'a>(rt: &Runtime, sub: &ArgMatches<'a, 'a>) -> Option<String> {
    debug!("Fetching id from commandline");
    sub.value_of("id").and_then(|s| Some(String::from(s)))
}

/*
 * Checks whether the commandline call was set to run the removal "checked",
 * so if another entry from the store refers to this ID, do not remove the file.
 */
fn run_removal_checking(env: &CommandEnv) -> bool {
    env.matches.is_present("check")
}
<commit_msg>Ensure we dont crash if there are no files found<commit_after>use runtime::Runtime;
use storage::backend::{StorageBackendError, StorageBackend};

use module::Module;
use module::ModuleError;
use module::CommandResult;
use module::CommandEnv;

use module::bm::header::build_header;
use module::bm::header::get_tags_from_header;
use storage::json::parser::JsonHeaderParser;
use storage::parser::{Parser, FileHeaderParser};
use storage::file::File;
use ui::file::{FilePrinter, TablePrinter};
use std::vec::IntoIter;

use clap::ArgMatches;
use regex::Regex;

pub fn add_command(module: &Module, env: CommandEnv) -> CommandResult {
    use url::Url;

    let url = env.matches.value_of("url").unwrap();

    if let Err(e) = Url::parse(url) {
        info!("Not an URL: '{}'", url);
        info!("  this will turn into an hard error before 0.1.0");
        debug!("URL parsing error: {:?}", e);
    }

    let tags = get_tags(env.rt, env.matches);
    info!("Adding url '{}' with tags '{:?}'", url, tags);

    let header  = build_header(&String::from(url), &tags);
    let file    = File::new_with_header(module, header);
    let parser  = Parser::new(JsonHeaderParser::new(None));
    let putres  = env.bk.put_file(file, &parser);

    putres.map_err(|sberr| {
        let mut err = ModuleError::new("Storage Backend Error");
        err.caused_by = Some(Box::new(sberr));
        err
    })
}

pub fn list_command(module: &Module, env: CommandEnv) -> CommandResult {
    let printer = TablePrinter::new(env.rt.is_verbose(), env.rt.is_debugging());
    let files   = get_filtered_files_from_backend(module, &env);

    debug!("Printing files now");
    files.map(|f| printer.print_files(f));

    Ok(())
}

pub fn remove_command(module: &Module, env: CommandEnv) -> CommandResult {
    let checked : bool = run_removal_checking(&env);
    debug!("Checked mode: {}", checked);
    if let Some(id) = get_id(env.rt, env.matches) {
        debug!("Remove by id: {}", id);

        let parser = Parser::new(JsonHeaderParser::new(None));
        env.bk.get_file_by_id(module, &id.into(), &parser).map(|file| {
            debug!("Remove file  : {:?}", file);

            if let Err(e) = env.bk.remove_file(module, file, checked) {
                debug!("Remove failed");
                let mut err = ModuleError::new("Removing file failed");
                err.caused_by = Some(Box::new(e));
                Err(err)
            } else {
                info!("Remove worked");
                Ok(())
            }
        }).unwrap_or({
            info!("No files found");
            Ok(())
        })
    } else {
        debug!("Remove more than one file");

        get_filtered_files_from_backend(module, &env).and_then(|files| {
            let nfiles = files.len();
            info!("Removing {} Files", nfiles);

            let errs = files.map(|file| {
                    debug!("Remove file: {:?}", file);
                    env.bk.remove_file(module, file, checked)
                })
                .filter(|e| e.is_err())
                .map(|e| {
                    let err = e.err().unwrap();
                    warn!("Error occured in Filesystem operation: {}", err);
                    err
                })
                .collect::<Vec<StorageBackendError>>();

            let nerrs = errs.len();

            if nerrs != 0 {
                warn!("{} Errors occured while removing {} files", nerrs, nfiles);
                let moderr = ModuleError::new("File removal failed");

                // TODO : Collect StorageBackendErrors

                Err(moderr)
            } else {
                Ok(())
            }
        })
    }
}

/*
 *
 * Private helpers
 *
 */

fn get_filtered_files_from_backend<'a>(module: &'a Module,
                                       env: &CommandEnv)
    -> Result<IntoIter<File<'a>>, ModuleError>
{
    let parser = Parser::new(JsonHeaderParser::new(None));
    let tags = get_tags(env.rt, env.matches);
    debug!("Tags: {:?}", tags);
    env.bk.iter_files(module, &parser)
        .map(|files| {
            let f = files.filter(|file| {
                debug!("Backend returns file: {:?}", file);
                if tags.len() != 0 {
                    debug!("Checking tags of: {:?}", file.id());
                    get_tags_from_header(&file.header()).iter()
                        .any(|t| tags.contains(t))
                } else {
                    true
                }
            }).filter(|file| {
                debug!("Checking matches of: {:?}", file.id());
                get_matcher(env.rt, env.matches)
                    .and_then(|r| Some(file.matches_with(&r)))
                    .unwrap_or(true)
            }).collect::<Vec<File>>();
            f.into_iter()
        }).map_err(|e| {
            debug!("Error from Backend: {:?}", e);
            let mut merr = ModuleError::new("Could not filter files");
            merr.caused_by = Some(Box::new(e));
            merr
        })
}

fn get_tags<'a>(rt: &Runtime, sub: &ArgMatches<'a, 'a>) -> Vec<String> {
    debug!("Fetching tags from commandline");
    sub.value_of("tags").and_then(|tags|
                                  Some(tags.split(",")
                                       .into_iter()
                                       .map(|s| s.to_string())
                                       .filter(|e|
                                            if e.contains(" ") {
                                                warn!("Tag contains spaces: '{}'", e);
                                                false
                                            } else {
                                                true
                                            }).collect()
                                      )
                                 ).or(Some(vec![])).unwrap()

}

fn get_matcher<'a>(rt: &Runtime, sub: &ArgMatches<'a, 'a>) -> Option<Regex> {
    debug!("Fetching matcher from commandline");
    if let Some(s) = sub.value_of("match") {
        if let Ok(r) = Regex::new(s) {
            return Some(r)
        } else {
            error!("Regex error, continuing without regex");
        }
    }
    None

}

fn get_id<'a>(rt: &Runtime, sub: &ArgMatches<'a, 'a>) -> Option<String> {
    debug!("Fetching id from commandline");
    sub.value_of("id").and_then(|s| Some(String::from(s)))
}

/*
 * Checks whether the commandline call was set to run the removal "checked",
 * so if another entry from the store refers to this ID, do not remove the file.
 */
fn run_removal_checking(env: &CommandEnv) -> bool {
    env.matches.is_present("check")
}
<|endoftext|>


<commit_before><commit_msg>Skeleton for problem 2390<commit_after>// https://leetcode.com/problems/removing-stars-from-a-string/
pub fn remove_stars(s: String) -> String {
    todo!()
}

fn main() {
    println!("{}", remove_stars("leet**cod*e".to_string())); // "lecoe"
    println!("{}", remove_stars("erase*****".to_string())); // ""
}
<|endoftext|>


<commit_before><commit_msg>HasMap's size<commit_after><|endoftext|>


<commit_before><commit_msg>Add Dijkstra<commit_after>use std::fs::File;
use std::io::BufReader;
use std::io::BufRead;
use std::collections::VecDeque;
use std::collections::BTreeSet;

const NODES_COUNT: usize = 5000;

type VertexTyp = i32;
type WeightTyp = f64;

const MAX_WEIGHT: WeightTyp = std::f64::INFINITY;

#[derive(Clone)]
struct Neighbor {
    target: VertexTyp,
    weight: WeightTyp
}

impl Neighbor {
	fn new(target: VertexTyp, weight: WeightTyp) -> Neighbor {
		Neighbor { target: target, weight: weight }
	}
}

// http://stackoverflow.com/questions/28247990/how-to-do-a-binary-search-on-a-vec-of-floats
#[derive(PartialEq, PartialOrd, Clone)]
struct NonNan(f64);
impl Eq for NonNan {}
impl Ord for NonNan {
	fn cmp(&self, other: &NonNan) -> std::cmp::Ordering {
		self.partial_cmp(other).unwrap()
	}
}

type AdjListTyp = Vec<Vec<Neighbor>>;

fn main() {
	let file = File::open("others/test.csv").unwrap();
	let reader = BufReader::new(&file);

	let mut adj_list: AdjListTyp = Vec::with_capacity(NODES_COUNT);
	adj_list.extend(std::iter::repeat(Vec::new()).take(NODES_COUNT));

	for line in reader.lines() {
		let res = line.unwrap();
		let mut split = res.split(",");
		let from = split.next().unwrap().parse::<usize>().unwrap();
		let to = split.next().unwrap().parse::<VertexTyp>().unwrap();
		let weight = split.next().unwrap().parse::<WeightTyp>().unwrap();

		adj_list[from].push(Neighbor::new(to, weight));
	}

	let mut min_dist: Vec<WeightTyp> = Vec::new();
	let mut previous: Vec<VertexTyp> = Vec::new();
	dijkstra_compute_paths(0, &adj_list, &mut min_dist, &mut previous);
	println!("Distance from 0 to 4: {}", min_dist[4]);

	let path: VecDeque<VertexTyp> = dijkstra_shortest_path(4, &previous);
	print!("Path : ");
	for node in path {
		print!("{} ", node);
	}
	println!("");
}

fn dijkstra_compute_paths(source: VertexTyp, adj_list: &AdjListTyp,
							min_dist: &mut Vec<WeightTyp>, previous: &mut Vec<VertexTyp>) {
	min_dist.clear();
	min_dist.extend(std::iter::repeat(MAX_WEIGHT).take(NODES_COUNT));

	min_dist[source as usize] = 0.0;

	previous.clear();
	previous.extend(std::iter::repeat(-1).take(NODES_COUNT));

	let mut vertex_queue: BTreeSet<(NonNan, VertexTyp)> = BTreeSet::new();
	vertex_queue.insert((NonNan(min_dist[source as usize]), source));

	while !vertex_queue.is_empty() {
		let first = vertex_queue.iter().cloned().next().unwrap();
		vertex_queue.remove(&first);
		let (NonNan(dist), u) = first;

		// Visit each edge exiting first
		let neighbors = &adj_list[first.1 as usize];
		for neighbor in neighbors {
			let v = neighbor.target as usize;
			let weight = neighbor.weight;

			let dist_through_first = dist + weight;
			if dist_through_first < min_dist[v] {
				vertex_queue.remove(&(NonNan(min_dist[v]), v as VertexTyp));

				min_dist[v] = dist_through_first;
				previous[v] = u;
				vertex_queue.insert((NonNan(min_dist[v]), v as VertexTyp));
			}
		}
	}
}

fn dijkstra_shortest_path(vertex: VertexTyp, previous: &Vec<VertexTyp>) -> VecDeque<VertexTyp> {
	let mut done = false;
	let mut path: VecDeque<VertexTyp> = VecDeque::new();
	let mut vertex = vertex;
	while !done {
		path.push_front(vertex);
		vertex = previous[vertex as usize];
		if vertex == -1 {
			done = true;
		}
	}
	path
}<|endoftext|>


<commit_before><commit_msg>Clippy pass<commit_after><|endoftext|>


<commit_before>//! Pieces pertaining to the HTTP message protocol.
use std::borrow::Cow;

use header::Connection;
use header::ConnectionOption::{KeepAlive, Close};
use header::Headers;
use version::HttpVersion;
use version::HttpVersion::{Http10, Http11};

pub use self::message::{HttpMessage, RequestHead, ResponseHead, Protocol};

pub mod h1;
pub mod h2;
pub mod message;

/// The raw status code and reason-phrase.
#[derive(Clone, PartialEq, Debug)]
pub struct RawStatus(pub u16, pub Cow<'static, str>);

/// Checks if a connection should be kept alive.
#[inline]
pub fn should_keep_alive(version: HttpVersion, headers: &Headers) -> bool {
    trace!("should_keep_alive( {:?}, {:?} )", version, headers.get::<Connection>());
    match (version, headers.get::<Connection>()) {
        (Http10, Some(conn)) if !conn.contains(&KeepAlive) => false,
        (Http11, Some(conn)) if conn.contains(&Close)  => false,
        _ => true
    }
}
<commit_msg>fix(http): no longer keep alive for Http1.0 if no Connection header<commit_after>//! Pieces pertaining to the HTTP message protocol.
use std::borrow::Cow;

use header::Connection;
use header::ConnectionOption::{KeepAlive, Close};
use header::Headers;
use version::HttpVersion;
use version::HttpVersion::{Http10, Http11};

pub use self::message::{HttpMessage, RequestHead, ResponseHead, Protocol};

pub mod h1;
pub mod h2;
pub mod message;

/// The raw status code and reason-phrase.
#[derive(Clone, PartialEq, Debug)]
pub struct RawStatus(pub u16, pub Cow<'static, str>);

/// Checks if a connection should be kept alive.
#[inline]
pub fn should_keep_alive(version: HttpVersion, headers: &Headers) -> bool {
    trace!("should_keep_alive( {:?}, {:?} )", version, headers.get::<Connection>());
    match (version, headers.get::<Connection>()) {
        (Http10, None) => false,
        (Http10, Some(conn)) if !conn.contains(&KeepAlive) => false,
        (Http11, Some(conn)) if conn.contains(&Close)  => false,
        _ => true
    }
}

#[test]
fn test_should_keep_alive() {
    let mut headers = Headers::new();

    assert!(!should_keep_alive(Http10, &headers));
    assert!(should_keep_alive(Http11, &headers));

    headers.set(Connection::close());
    assert!(!should_keep_alive(Http10, &headers));
    assert!(!should_keep_alive(Http11, &headers));

    headers.set(Connection::keep_alive());
    assert!(should_keep_alive(Http10, &headers));
    assert!(should_keep_alive(Http11, &headers));
}
<|endoftext|>


<commit_before>use std::cmp::max;
use std::collections::VecDeque;
use std::mem::size_of;
use std::{ptr, slice};

use super::{Color, Event, Font, Image, Rect};

use system::error::{Error, Result, EINVAL};

pub struct Window {
    pub x: i32,
    pub y: i32,
    image: Image,
    title: String,
    title_image: Image,
    events: VecDeque<Event>,
}

impl Window {
    pub fn new(x: i32, y: i32, w: i32, h: i32, title: String) -> Window {
        let mut title_image = Image::new(title.chars().count() as i32 * 8, 16);
        title_image.as_roi().set(Color::rgba(0, 0, 0, 0));
        {
            let mut x = 0;
            for c in title.chars() {
                title_image.roi(&Rect::new(x, 0, 8, 16)).blend(&Font::render(c, Color::rgb(255, 255, 255)).as_roi());
                x += 8;
            }
        }

        Window {
            x: x,
            y: y,
            image: Image::new(w, h),
            title: title,
            title_image: title_image,
            events: VecDeque::new()
        }
    }

    pub fn width(&self) -> i32 {
        self.image.width()
    }

    pub fn height(&self) -> i32 {
        self.image.height()
    }

    pub fn rect(&self) -> Rect {
        Rect::new(self.x, self.y, self.width(), self.height())
    }

    pub fn title_rect(&self) -> Rect {
        if self.title.is_empty() {
            Rect::default()
        } else {
            Rect::new(self.x, self.y - 18, self.width(), 18)
        }
    }

    pub fn exit_contains(&self, x: i32, y: i32) -> bool {
        ! self.title.is_empty() && x >= max(self.x, self.x + self.width() - 10)  && y >= self.y - 18 && x < self.x + self.width() && y < self.y
    }

    pub fn draw_title(&mut self, image: &mut Image, rect: &Rect, focused: bool) {
        let title_rect = self.title_rect();
        let title_intersect = rect.intersection(&title_rect);
        if ! title_intersect.is_empty() {
            if focused {
                image.roi(&title_intersect).set(Color::rgb(192, 192, 192));
            } else {
                image.roi(&title_intersect).set(Color::rgb(64, 64, 64));
            }

            {
                let image_rect = Rect::new(title_rect.left() + 4, title_rect.top() + 1, self.title_image.width(), self.title_image.height());
                let image_intersect = rect.intersection(&image_rect);
                if ! image_intersect.is_empty() {
                    image.roi(&image_intersect).blend(&self.title_image.roi(&image_intersect.offset(-image_rect.left(), -image_rect.top())));
                }
            }

            let x = max(self.x + 2, self.x + self.width() - 10);
            if x + 10 <= self.x + self.width() {
                let mut font_image = Font::render('X', Color::rgb(255, 255, 255));
                let image_rect = Rect::new(x, title_rect.top() + 1, font_image.width(), font_image.height());
                let image_intersect = rect.intersection(&image_rect);
                if ! image_intersect.is_empty() {
                    image.roi(&image_intersect).blend(&font_image.roi(&image_intersect.offset(-image_rect.left(), -image_rect.top())));
                }
            }
        }
    }

    pub fn draw(&mut self, image: &mut Image, rect: &Rect) {
        let self_rect = self.rect();
        let intersect = self_rect.intersection(&rect);
        if ! intersect.is_empty() {
            image.roi(&intersect).blit(&self.image.roi(&intersect.offset(-self_rect.left(), -self_rect.top())));
        }
    }

    pub fn event(&mut self, event: Event) {
        self.events.push_back(event);
    }

    pub fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
        if buf.len() >= size_of::<Event>() {
            let mut i = 0;
            while i <= buf.len() - size_of::<Event>() {
                if let Some(event) = self.events.pop_front() {
                    unsafe { ptr::write(buf.as_mut_ptr().offset(i as isize) as *mut Event, event) };
                    i += size_of::<Event>();
                } else {
                    break;
                }
            }
            Ok(i)
        } else {
            Err(Error::new(EINVAL))
        }
    }

    pub fn write(&mut self, buf: &[u8]) -> Result<usize> {
        let old = self.image.data_mut();
        let new = unsafe { slice::from_raw_parts(buf.as_ptr() as *const Color, buf.len() / size_of::<Color>()) };

        let mut i = 0;
        while i < old.len() && i < new.len() {
            old[i] = new[i];
            i += 1;
        }

        Ok(i * size_of::<Color>())
    }

    pub fn path(&self, buf: &mut [u8]) -> Result<usize> {
        let mut i = 0;
        let path_str = format!("orbital:/{}/{}/{}/{}/{}", self.x, self.y, self.width(), self.height(), self.title);
        let path = path_str.as_bytes();
        while i < buf.len() && i < path.len() {
            buf[i] = path[i];
            i += 1;
        }
        Ok(i)
    }
}
<commit_msg>Correct rendering of title<commit_after>use std::cmp::max;
use std::collections::VecDeque;
use std::mem::size_of;
use std::{ptr, slice};

use super::{Color, Event, Font, Image, Rect};

use system::error::{Error, Result, EINVAL};

pub struct Window {
    pub x: i32,
    pub y: i32,
    image: Image,
    title: String,
    events: VecDeque<Event>,
}

impl Window {
    pub fn new(x: i32, y: i32, w: i32, h: i32, title: String) -> Window {
        Window {
            x: x,
            y: y,
            image: Image::new(w, h),
            title: title,
            events: VecDeque::new()
        }
    }

    pub fn width(&self) -> i32 {
        self.image.width()
    }

    pub fn height(&self) -> i32 {
        self.image.height()
    }

    pub fn rect(&self) -> Rect {
        Rect::new(self.x, self.y, self.width(), self.height())
    }

    pub fn title_rect(&self) -> Rect {
        if self.title.is_empty() {
            Rect::default()
        } else {
            Rect::new(self.x, self.y - 18, self.width(), 18)
        }
    }

    pub fn exit_contains(&self, x: i32, y: i32) -> bool {
        ! self.title.is_empty() && x >= max(self.x, self.x + self.width() - 10)  && y >= self.y - 18 && x < self.x + self.width() && y < self.y
    }

    pub fn draw_title(&mut self, image: &mut Image, rect: &Rect, focused: bool) {
        let title_rect = self.title_rect();
        let title_intersect = rect.intersection(&title_rect);
        if ! title_intersect.is_empty() {
            if focused {
                image.roi(&title_intersect).set(Color::rgb(192, 192, 192));
            } else {
                image.roi(&title_intersect).set(Color::rgb(64, 64, 64));
            }

            let mut x = self.x + 2;
            for c in self.title.chars() {
                if x < max(self.x + 2, self.x + self.width() - 10) {
                    let mut font_image = Font::render(c, Color::rgb(255, 255, 255));
                    let image_rect = Rect::new(x, title_rect.top() + 1, font_image.width(), font_image.height());
                    let image_intersect = rect.intersection(&image_rect);
                    if ! image_intersect.is_empty() {
                        image.roi(&image_intersect).blend(&font_image.roi(&image_intersect.offset(-image_rect.left(), -image_rect.top())));
                    }
                    x += 8;
                } else {
                    break;
                }
            }

            x = max(self.x + 2, self.x + self.width() - 10);
            if x + 10 <= self.x + self.width() {
                let mut font_image = Font::render('X', Color::rgb(255, 255, 255));
                let image_rect = Rect::new(x, title_rect.top() + 1, font_image.width(), font_image.height());
                let image_intersect = rect.intersection(&image_rect);
                if ! image_intersect.is_empty() {
                    image.roi(&image_intersect).blend(&font_image.roi(&image_intersect.offset(-image_rect.left(), -image_rect.top())));
                }
            }
        }
    }

    pub fn draw(&mut self, image: &mut Image, rect: &Rect) {
        let self_rect = self.rect();
        let intersect = self_rect.intersection(&rect);
        if ! intersect.is_empty() {
            image.roi(&intersect).blit(&self.image.roi(&intersect.offset(-self_rect.left(), -self_rect.top())));
        }
    }

    pub fn event(&mut self, event: Event) {
        self.events.push_back(event);
    }

    pub fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
        if buf.len() >= size_of::<Event>() {
            let mut i = 0;
            while i <= buf.len() - size_of::<Event>() {
                if let Some(event) = self.events.pop_front() {
                    unsafe { ptr::write(buf.as_mut_ptr().offset(i as isize) as *mut Event, event) };
                    i += size_of::<Event>();
                } else {
                    break;
                }
            }
            Ok(i)
        } else {
            Err(Error::new(EINVAL))
        }
    }

    pub fn write(&mut self, buf: &[u8]) -> Result<usize> {
        let old = self.image.data_mut();
        let new = unsafe { slice::from_raw_parts(buf.as_ptr() as *const Color, buf.len() / size_of::<Color>()) };

        let mut i = 0;
        while i < old.len() && i < new.len() {
            old[i] = new[i];
            i += 1;
        }

        Ok(i * size_of::<Color>())
    }

    pub fn path(&self, buf: &mut [u8]) -> Result<usize> {
        let mut i = 0;
        let path_str = format!("orbital:/{}/{}/{}/{}/{}", self.x, self.y, self.width(), self.height(), self.title);
        let path = path_str.as_bytes();
        while i < buf.len() && i < path.len() {
            buf[i] = path[i];
            i += 1;
        }
        Ok(i)
    }
}
<|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/. */

use dom::bindings::codegen::BindingDeclarations::HTMLHtmlElementBinding;
use dom::bindings::codegen::InheritTypes::HTMLHtmlElementDerived;
use dom::bindings::js::{JSRef, Temporary};
use dom::bindings::error::ErrorResult;
use dom::document::Document;
use dom::element::HTMLHtmlElementTypeId;
use dom::eventtarget::{EventTarget, NodeTargetTypeId};
use dom::htmlelement::HTMLElement;
use dom::node::{Node, ElementNodeTypeId};
use servo_util::str::DOMString;

#[deriving(Encodable)]
pub struct HTMLHtmlElement {
    pub htmlelement: HTMLElement
}

impl HTMLHtmlElementDerived for EventTarget {
    fn is_htmlhtmlelement(&self) -> bool {
        self.type_id == NodeTargetTypeId(ElementNodeTypeId(HTMLHtmlElementTypeId))
    }
}

impl HTMLHtmlElement {
    pub fn new_inherited(localName: DOMString, document: &JSRef<Document>) -> HTMLHtmlElement {
        HTMLHtmlElement {
            htmlelement: HTMLElement::new_inherited(HTMLHtmlElementTypeId, localName, document)
        }
    }

    pub fn new(localName: DOMString, document: &JSRef<Document>) -> Temporary<HTMLHtmlElement> {
        let element = HTMLHtmlElement::new_inherited(localName, document);
        Node::reflect_node(box element, document, HTMLHtmlElementBinding::Wrap)
    }
}

pub trait HTMLHtmlElementMethods {
    fn Version(&self) -> DOMString;
    fn SetVersion(&mut self, _version: DOMString) -> ErrorResult;
}

impl<'a> HTMLHtmlElementMethods for JSRef<'a, HTMLHtmlElement> {
    fn Version(&self) -> DOMString {
        "".to_owned()
    }

    fn SetVersion(&mut self, _version: DOMString) -> ErrorResult {
        Ok(())
    }
}
<commit_msg>Remove needless '&mut self' from HTMLHtmlElementMethods.<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/. */

use dom::bindings::codegen::BindingDeclarations::HTMLHtmlElementBinding;
use dom::bindings::codegen::InheritTypes::HTMLHtmlElementDerived;
use dom::bindings::js::{JSRef, Temporary};
use dom::bindings::error::ErrorResult;
use dom::document::Document;
use dom::element::HTMLHtmlElementTypeId;
use dom::eventtarget::{EventTarget, NodeTargetTypeId};
use dom::htmlelement::HTMLElement;
use dom::node::{Node, ElementNodeTypeId};
use servo_util::str::DOMString;

#[deriving(Encodable)]
pub struct HTMLHtmlElement {
    pub htmlelement: HTMLElement
}

impl HTMLHtmlElementDerived for EventTarget {
    fn is_htmlhtmlelement(&self) -> bool {
        self.type_id == NodeTargetTypeId(ElementNodeTypeId(HTMLHtmlElementTypeId))
    }
}

impl HTMLHtmlElement {
    pub fn new_inherited(localName: DOMString, document: &JSRef<Document>) -> HTMLHtmlElement {
        HTMLHtmlElement {
            htmlelement: HTMLElement::new_inherited(HTMLHtmlElementTypeId, localName, document)
        }
    }

    pub fn new(localName: DOMString, document: &JSRef<Document>) -> Temporary<HTMLHtmlElement> {
        let element = HTMLHtmlElement::new_inherited(localName, document);
        Node::reflect_node(box element, document, HTMLHtmlElementBinding::Wrap)
    }
}

pub trait HTMLHtmlElementMethods {
    fn Version(&self) -> DOMString;
    fn SetVersion(&self, _version: DOMString) -> ErrorResult;
}

impl<'a> HTMLHtmlElementMethods for JSRef<'a, HTMLHtmlElement> {
    fn Version(&self) -> DOMString {
        "".to_owned()
    }

    fn SetVersion(&self, _version: DOMString) -> ErrorResult {
        Ok(())
    }
}
<|endoftext|>


<commit_before><commit_msg>`FromHexError` isn't a good choice to use it in `FromStr`<commit_after><|endoftext|>


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

// Used to cause ICE

static VEC: [u32, ..256] = vec!(); //~ ERROR mismatched types

fn main() {}

<|endoftext|>


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

// error-pattern: requires `copy` lang_item

#![feature(lang_items, start)]
#![no_std]

#[lang = "sized"]
trait Sized {}

#[start]
fn main(_: int, _: *const *const u8) -> int {
    0
}
<|endoftext|>


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

#![allow(dead_code)]

trait MultiDispatch<T> {
    type O;
}

trait Trait: Sized {
    type A: MultiDispatch<Self::B, O = Self>;
    type B;

    fn new<U>(u: U) -> <Self::A as MultiDispatch<U>>::O where Self::A : MultiDispatch<U>;
}

fn test<T: Trait<B=i32>>(b: i32) -> T where T::A: MultiDispatch<i32> { T::new(b) }
//~^ ERROR type mismatch resolving

fn main() {}
<|endoftext|>


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

use rustc::hir;
use rustc::mir::*;
use rustc::ty;
use rustc_data_structures::indexed_vec::Idx;
use rustc_errors::DiagnosticBuilder;
use syntax_pos::Span;

use borrow_check::MirBorrowckCtxt;
use dataflow::move_paths::{IllegalMoveOrigin, IllegalMoveOriginKind};
use dataflow::move_paths::{LookupResult, MoveError, MovePathIndex};
use util::borrowck_errors::{BorrowckErrors, Origin};

// Often when desugaring a pattern match we may have many individual moves in
// MIR that are all part of one operation from the user's point-of-view. For
// example:
//
// let (x, y) = foo()
//
// would move x from the 0 field of some temporary, and y from the 1 field. We
// group such errors together for cleaner error reporting.
//
// Errors are kept separate if they are from places with different parent move
// paths. For example, this generates two errors:
//
// let (&x, &y) = (&String::new(), &String::new());
#[derive(Debug)]
enum GroupedMoveError<'tcx> {
    // Match place can't be moved from
    // e.g. match x[0] { s => (), } where x: &[String]
    MovesFromMatchPlace {
        span: Span,
        move_from: Place<'tcx>,
        kind: IllegalMoveOriginKind<'tcx>,
        binds_to: Vec<Local>,
    },
    // Part of a pattern can't be moved from,
    // e.g. match &String::new() { &x => (), }
    MovesFromPattern {
        span: Span,
        move_from: MovePathIndex,
        kind: IllegalMoveOriginKind<'tcx>,
        binds_to: Vec<Local>,
    },
    // Everything that isn't from pattern matching.
    OtherIllegalMove {
        span: Span,
        kind: IllegalMoveOriginKind<'tcx>,
    },
}

impl<'a, 'gcx, 'tcx> MirBorrowckCtxt<'a, 'gcx, 'tcx> {
    pub(crate) fn report_move_errors(&self, move_errors: Vec<MoveError<'tcx>>) {
        let grouped_errors = self.group_move_errors(move_errors);
        for error in grouped_errors {
            self.report(error);
        }
    }

    fn group_move_errors(&self, errors: Vec<MoveError<'tcx>>) -> Vec<GroupedMoveError<'tcx>> {
        let mut grouped_errors = Vec::new();
        for error in errors {
            self.append_to_grouped_errors(&mut grouped_errors, error);
        }
        grouped_errors
    }

    fn append_to_grouped_errors(
        &self,
        grouped_errors: &mut Vec<GroupedMoveError<'tcx>>,
        error: MoveError<'tcx>,
    ) {
        match error {
            MoveError::UnionMove { .. } => {
                unimplemented!("don't know how to report union move errors yet.")
            }
            MoveError::IllegalMove {
                cannot_move_out_of: IllegalMoveOrigin { location, kind },
            } => {
                let stmt_source_info = self.mir.source_info(location);
                if let Some(StatementKind::Assign(
                    Place::Local(local),
                    Rvalue::Use(Operand::Move(move_from)),
                )) = self.mir.basic_blocks()[location.block]
                    .statements
                    .get(location.statement_index)
                    .map(|stmt| &stmt.kind)
                {
                    let local_decl = &self.mir.local_decls[*local];
                    if let Some(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
                        opt_match_place: Some((ref opt_match_place, match_span)),
                        binding_mode: _,
                        opt_ty_info: _,
                    }))) = local_decl.is_user_variable
                    {
                        // opt_match_place is the
                        // match_span is the span of the expression being matched on
                        // match *x.y { ... }        match_place is Some(*x.y)
                        //       ^^^^                match_span is the span of *x.y
                        // opt_match_place is None for let [mut] x = ... statements,
                        // whether or not the right-hand side is a place expression

                        // HACK use scopes to determine if this assignment is
                        // the initialization of a variable.
                        // FIXME(matthewjasper) This would probably be more
                        // reliable if it used the ever initialized dataflow
                        // but move errors are currently reported before the
                        // rest of borrowck has run.
                        if self
                            .mir
                            .is_sub_scope(local_decl.source_info.scope, stmt_source_info.scope)
                        {
                            self.append_binding_error(
                                grouped_errors,
                                kind,
                                move_from,
                                *local,
                                opt_match_place,
                                match_span,
                            );
                        }
                        return;
                    }
                }
                grouped_errors.push(GroupedMoveError::OtherIllegalMove {
                    span: stmt_source_info.span,
                    kind,
                });
            }
        }
    }

    fn append_binding_error(
        &self,
        grouped_errors: &mut Vec<GroupedMoveError<'tcx>>,
        kind: IllegalMoveOriginKind<'tcx>,
        move_from: &Place<'tcx>,
        bind_to: Local,
        match_place: &Option<Place<'tcx>>,
        match_span: Span,
    ) {
        debug!(
            "append_to_grouped_errors(match_place={:?}, match_span={:?})",
            match_place, match_span
        );

        let from_simple_let = match_place.is_none();
        let match_place = match_place.as_ref().unwrap_or(move_from);

        match self.move_data.rev_lookup.find(match_place) {
            // Error with the match place
            LookupResult::Parent(_) => {
                for ge in &mut *grouped_errors {
                    if let GroupedMoveError::MovesFromMatchPlace { span, binds_to, .. } = ge {
                        if match_span == *span {
                            debug!("appending local({:?}) to list", bind_to);
                            if !binds_to.is_empty() {
                                binds_to.push(bind_to);
                            }
                            return;
                        }
                    }
                }
                debug!("found a new move error location");

                // Don't need to point to x in let x = ... .
                let binds_to = if from_simple_let {
                    vec![]
                } else {
                    vec![bind_to]
                };
                grouped_errors.push(GroupedMoveError::MovesFromMatchPlace {
                    span: match_span,
                    move_from: match_place.clone(),
                    kind,
                    binds_to,
                });
            }
            // Error with the pattern
            LookupResult::Exact(_) => {
                let mpi = match self.move_data.rev_lookup.find(move_from) {
                    LookupResult::Parent(Some(mpi)) => mpi,
                    // move_from should be a projection from match_place.
                    _ => unreachable!("Probably not unreachable..."),
                };
                for ge in &mut *grouped_errors {
                    if let GroupedMoveError::MovesFromPattern {
                        span,
                        move_from: other_mpi,
                        binds_to,
                        ..
                    } = ge
                    {
                        if match_span == *span && mpi == *other_mpi {
                            debug!("appending local({:?}) to list", bind_to);
                            binds_to.push(bind_to);
                            return;
                        }
                    }
                }
                debug!("found a new move error location");
                grouped_errors.push(GroupedMoveError::MovesFromPattern {
                    span: match_span,
                    move_from: mpi,
                    kind,
                    binds_to: vec![bind_to],
                });
            }
        };
    }

    fn report(&self, error: GroupedMoveError<'tcx>) {
        let (mut err, err_span) = {
            let (span, kind): (Span, &IllegalMoveOriginKind) = match error {
                GroupedMoveError::MovesFromMatchPlace { span, ref kind, .. }
                | GroupedMoveError::MovesFromPattern { span, ref kind, .. }
                | GroupedMoveError::OtherIllegalMove { span, ref kind } => (span, kind),
            };
            let origin = Origin::Mir;
            (
                match kind {
                    IllegalMoveOriginKind::Static => {
                        self.tcx.cannot_move_out_of(span, "static item", origin)
                    }
                    IllegalMoveOriginKind::BorrowedContent { target_place: place } => {
                        // Inspect the type of the content behind the
                        // borrow to provide feedback about why this
                        // was a move rather than a copy.
                        let ty = place.ty(self.mir, self.tcx).to_ty(self.tcx);
                        match ty.sty {
                            ty::TyArray(..) | ty::TySlice(..) => self
                                .tcx
                                .cannot_move_out_of_interior_noncopy(span, ty, None, origin),
                            ty::TyClosure(def_id, closure_substs)
                                if !self.mir.upvar_decls.is_empty()
                                    && {
                                        match place {
                                            Place::Projection(ref proj) => {
                                                proj.base == Place::Local(Local::new(1))
                                            }
                                            Place::Local(_) | Place::Static(_) => unreachable!(),
                                        }
                                    } =>
                            {
                                let closure_kind_ty =
                                    closure_substs.closure_kind_ty(def_id, self.tcx);
                                let closure_kind = closure_kind_ty.to_opt_closure_kind();
                                let place_description = match closure_kind {
                                    Some(ty::ClosureKind::Fn) => {
                                        "captured variable in an `Fn` closure"
                                    }
                                    Some(ty::ClosureKind::FnMut) => {
                                        "captured variable in an `FnMut` closure"
                                    }
                                    Some(ty::ClosureKind::FnOnce) => {
                                        bug!("closure kind does not match first argument type")
                                    }
                                    None => bug!("closure kind not inferred by borrowck"),
                                };
                                self.tcx.cannot_move_out_of(span, place_description, origin)
                            }
                            _ => self
                                .tcx
                                .cannot_move_out_of(span, "borrowed content", origin),
                        }
                    }
                    IllegalMoveOriginKind::InteriorOfTypeWithDestructor { container_ty: ty } => {
                        self.tcx
                            .cannot_move_out_of_interior_of_drop(span, ty, origin)
                    }
                    IllegalMoveOriginKind::InteriorOfSliceOrArray { ty, is_index } => self
                        .tcx
                        .cannot_move_out_of_interior_noncopy(span, ty, Some(*is_index), origin),
                },
                span,
            )
        };

        self.add_move_hints(error, &mut err, err_span);
        err.emit();
    }

    fn add_move_hints(
        &self,
        error: GroupedMoveError<'tcx>,
        err: &mut DiagnosticBuilder<'a>,
        span: Span,
    ) {
        match error {
            GroupedMoveError::MovesFromMatchPlace {
                mut binds_to,
                move_from,
                ..
            } => {
                // Ok to suggest a borrow, since the target can't be moved from
                // anyway.
                if let Ok(snippet) = self.tcx.sess.codemap().span_to_snippet(span) {
                    match move_from {
                        Place::Projection(ref proj)
                            if self.suitable_to_remove_deref(proj, &snippet) =>
                        {
                            err.span_suggestion(
                                span,
                                "consider removing this dereference operator",
                                format!("{}", &snippet[1..]),
                            );
                        }
                        _ => {
                            err.span_suggestion(
                                span,
                                "consider using a reference instead",
                                format!("&{}", snippet),
                            );
                        }
                    }

                    binds_to.sort();
                    binds_to.dedup();
                    for local in binds_to {
                        let bind_to = &self.mir.local_decls[local];
                        let binding_span = bind_to.source_info.span;
                        err.span_label(
                            binding_span,
                            format!(
                                "move occurs because {} has type `{}`, \
                                 which does not implement the `Copy` trait",
                                bind_to.name.unwrap(),
                                bind_to.ty
                            ),
                        );
                    }
                }
            }
            GroupedMoveError::MovesFromPattern { mut binds_to, .. } => {
                // Suggest ref, since there might be a move in
                // another match arm
                binds_to.sort();
                binds_to.dedup();
                for local in binds_to {
                    let bind_to = &self.mir.local_decls[local];
                    let binding_span = bind_to.source_info.span;

                    // Suggest ref mut when the user has already written mut.
                    let ref_kind = match bind_to.mutability {
                        Mutability::Not => "ref",
                        Mutability::Mut => "ref mut",
                    };
                    match bind_to.name {
                        Some(name) => {
                            err.span_suggestion(
                                binding_span,
                                "to prevent move, use ref or ref mut",
                                format!("{} {:?}", ref_kind, name),
                            );
                        }
                        None => {
                            err.span_label(
                                span,
                                format!("Local {:?} is not suitable for ref", bind_to),
                            );
                        }
                    }
                }
            }
            // Nothing to suggest.
            GroupedMoveError::OtherIllegalMove { .. } => (),
        }
    }

    fn suitable_to_remove_deref(&self, proj: &PlaceProjection<'tcx>, snippet: &str) -> bool {
        let is_shared_ref = |ty: ty::Ty| match ty.sty {
            ty::TypeVariants::TyRef(.., hir::Mutability::MutImmutable) => true,
            _ => false,
        };

        proj.elem == ProjectionElem::Deref && snippet.starts_with('*') && match proj.base {
            Place::Local(local) => {
                let local_decl = &self.mir.local_decls[local];
                // If this is a temporary, then this could be from an
                // overloaded * operator.
                local_decl.is_user_variable.is_some() && is_shared_ref(local_decl.ty)
            }
            Place::Static(ref st) => is_shared_ref(st.ty),
            Place::Projection(ref proj) => match proj.elem {
                ProjectionElem::Field(_, ty) => is_shared_ref(ty),
                _ => false,
            },
        }
    }
}
<commit_msg>Fix #52416 - ice for move errors in unsafe blocks<commit_after>// Copyright 2018 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.

use rustc::hir;
use rustc::mir::*;
use rustc::ty;
use rustc_data_structures::indexed_vec::Idx;
use rustc_errors::DiagnosticBuilder;
use syntax_pos::Span;

use borrow_check::MirBorrowckCtxt;
use dataflow::move_paths::{IllegalMoveOrigin, IllegalMoveOriginKind};
use dataflow::move_paths::{LookupResult, MoveError, MovePathIndex};
use util::borrowck_errors::{BorrowckErrors, Origin};

// Often when desugaring a pattern match we may have many individual moves in
// MIR that are all part of one operation from the user's point-of-view. For
// example:
//
// let (x, y) = foo()
//
// would move x from the 0 field of some temporary, and y from the 1 field. We
// group such errors together for cleaner error reporting.
//
// Errors are kept separate if they are from places with different parent move
// paths. For example, this generates two errors:
//
// let (&x, &y) = (&String::new(), &String::new());
#[derive(Debug)]
enum GroupedMoveError<'tcx> {
    // Match place can't be moved from
    // e.g. match x[0] { s => (), } where x: &[String]
    MovesFromMatchPlace {
        span: Span,
        move_from: Place<'tcx>,
        kind: IllegalMoveOriginKind<'tcx>,
        binds_to: Vec<Local>,
    },
    // Part of a pattern can't be moved from,
    // e.g. match &String::new() { &x => (), }
    MovesFromPattern {
        span: Span,
        move_from: MovePathIndex,
        kind: IllegalMoveOriginKind<'tcx>,
        binds_to: Vec<Local>,
    },
    // Everything that isn't from pattern matching.
    OtherIllegalMove {
        span: Span,
        kind: IllegalMoveOriginKind<'tcx>,
    },
}

impl<'a, 'gcx, 'tcx> MirBorrowckCtxt<'a, 'gcx, 'tcx> {
    pub(crate) fn report_move_errors(&self, move_errors: Vec<MoveError<'tcx>>) {
        let grouped_errors = self.group_move_errors(move_errors);
        for error in grouped_errors {
            self.report(error);
        }
    }

    fn group_move_errors(&self, errors: Vec<MoveError<'tcx>>) -> Vec<GroupedMoveError<'tcx>> {
        let mut grouped_errors = Vec::new();
        for error in errors {
            self.append_to_grouped_errors(&mut grouped_errors, error);
        }
        grouped_errors
    }

    fn append_to_grouped_errors(
        &self,
        grouped_errors: &mut Vec<GroupedMoveError<'tcx>>,
        error: MoveError<'tcx>,
    ) {
        match error {
            MoveError::UnionMove { .. } => {
                unimplemented!("don't know how to report union move errors yet.")
            }
            MoveError::IllegalMove {
                cannot_move_out_of: IllegalMoveOrigin { location, kind },
            } => {
                let stmt_source_info = self.mir.source_info(location);
                if let Some(StatementKind::Assign(
                    Place::Local(local),
                    Rvalue::Use(Operand::Move(move_from)),
                )) = self.mir.basic_blocks()[location.block]
                    .statements
                    .get(location.statement_index)
                    .map(|stmt| &stmt.kind)
                {
                    let local_decl = &self.mir.local_decls[*local];
                    // opt_match_place is the
                    // match_span is the span of the expression being matched on
                    // match *x.y { ... }        match_place is Some(*x.y)
                    //       ^^^^                match_span is the span of *x.y
                    //
                    // opt_match_place is None for let [mut] x = ... statements,
                    // whether or not the right-hand side is a place expression
                    if let Some(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
                        opt_match_place: Some((ref opt_match_place, match_span)),
                        binding_mode: _,
                        opt_ty_info: _,
                    }))) = local_decl.is_user_variable
                    {
                        // HACK use scopes to determine if this assignment is
                        // the initialization of a variable.
                        // FIXME(matthewjasper) This would probably be more
                        // reliable if it used the ever initialized dataflow
                        // but move errors are currently reported before the
                        // rest of borrowck has run.
                        if self
                            .mir
                            .is_sub_scope(local_decl.source_info.scope, stmt_source_info.scope)
                        {
                            self.append_binding_error(
                                grouped_errors,
                                kind,
                                move_from,
                                *local,
                                opt_match_place,
                                match_span,
                            );
                            return;
                        }
                    }
                }
                grouped_errors.push(GroupedMoveError::OtherIllegalMove {
                    span: stmt_source_info.span,
                    kind,
                });
            }
        }
    }

    fn append_binding_error(
        &self,
        grouped_errors: &mut Vec<GroupedMoveError<'tcx>>,
        kind: IllegalMoveOriginKind<'tcx>,
        move_from: &Place<'tcx>,
        bind_to: Local,
        match_place: &Option<Place<'tcx>>,
        match_span: Span,
    ) {
        debug!(
            "append_to_grouped_errors(match_place={:?}, match_span={:?})",
            match_place, match_span
        );

        let from_simple_let = match_place.is_none();
        let match_place = match_place.as_ref().unwrap_or(move_from);

        match self.move_data.rev_lookup.find(match_place) {
            // Error with the match place
            LookupResult::Parent(_) => {
                for ge in &mut *grouped_errors {
                    if let GroupedMoveError::MovesFromMatchPlace { span, binds_to, .. } = ge {
                        if match_span == *span {
                            debug!("appending local({:?}) to list", bind_to);
                            if !binds_to.is_empty() {
                                binds_to.push(bind_to);
                            }
                            return;
                        }
                    }
                }
                debug!("found a new move error location");

                // Don't need to point to x in let x = ... .
                let binds_to = if from_simple_let {
                    vec![]
                } else {
                    vec![bind_to]
                };
                grouped_errors.push(GroupedMoveError::MovesFromMatchPlace {
                    span: match_span,
                    move_from: match_place.clone(),
                    kind,
                    binds_to,
                });
            }
            // Error with the pattern
            LookupResult::Exact(_) => {
                let mpi = match self.move_data.rev_lookup.find(move_from) {
                    LookupResult::Parent(Some(mpi)) => mpi,
                    // move_from should be a projection from match_place.
                    _ => unreachable!("Probably not unreachable..."),
                };
                for ge in &mut *grouped_errors {
                    if let GroupedMoveError::MovesFromPattern {
                        span,
                        move_from: other_mpi,
                        binds_to,
                        ..
                    } = ge
                    {
                        if match_span == *span && mpi == *other_mpi {
                            debug!("appending local({:?}) to list", bind_to);
                            binds_to.push(bind_to);
                            return;
                        }
                    }
                }
                debug!("found a new move error location");
                grouped_errors.push(GroupedMoveError::MovesFromPattern {
                    span: match_span,
                    move_from: mpi,
                    kind,
                    binds_to: vec![bind_to],
                });
            }
        };
    }

    fn report(&self, error: GroupedMoveError<'tcx>) {
        let (mut err, err_span) = {
            let (span, kind): (Span, &IllegalMoveOriginKind) = match error {
                GroupedMoveError::MovesFromMatchPlace { span, ref kind, .. }
                | GroupedMoveError::MovesFromPattern { span, ref kind, .. }
                | GroupedMoveError::OtherIllegalMove { span, ref kind } => (span, kind),
            };
            let origin = Origin::Mir;
            (
                match kind {
                    IllegalMoveOriginKind::Static => {
                        self.tcx.cannot_move_out_of(span, "static item", origin)
                    }
                    IllegalMoveOriginKind::BorrowedContent { target_place: place } => {
                        // Inspect the type of the content behind the
                        // borrow to provide feedback about why this
                        // was a move rather than a copy.
                        let ty = place.ty(self.mir, self.tcx).to_ty(self.tcx);
                        match ty.sty {
                            ty::TyArray(..) | ty::TySlice(..) => self
                                .tcx
                                .cannot_move_out_of_interior_noncopy(span, ty, None, origin),
                            ty::TyClosure(def_id, closure_substs)
                                if !self.mir.upvar_decls.is_empty()
                                    && {
                                        match place {
                                            Place::Projection(ref proj) => {
                                                proj.base == Place::Local(Local::new(1))
                                            }
                                            Place::Local(_) | Place::Static(_) => unreachable!(),
                                        }
                                    } =>
                            {
                                let closure_kind_ty =
                                    closure_substs.closure_kind_ty(def_id, self.tcx);
                                let closure_kind = closure_kind_ty.to_opt_closure_kind();
                                let place_description = match closure_kind {
                                    Some(ty::ClosureKind::Fn) => {
                                        "captured variable in an `Fn` closure"
                                    }
                                    Some(ty::ClosureKind::FnMut) => {
                                        "captured variable in an `FnMut` closure"
                                    }
                                    Some(ty::ClosureKind::FnOnce) => {
                                        bug!("closure kind does not match first argument type")
                                    }
                                    None => bug!("closure kind not inferred by borrowck"),
                                };
                                self.tcx.cannot_move_out_of(span, place_description, origin)
                            }
                            _ => self
                                .tcx
                                .cannot_move_out_of(span, "borrowed content", origin),
                        }
                    }
                    IllegalMoveOriginKind::InteriorOfTypeWithDestructor { container_ty: ty } => {
                        self.tcx
                            .cannot_move_out_of_interior_of_drop(span, ty, origin)
                    }
                    IllegalMoveOriginKind::InteriorOfSliceOrArray { ty, is_index } => self
                        .tcx
                        .cannot_move_out_of_interior_noncopy(span, ty, Some(*is_index), origin),
                },
                span,
            )
        };

        self.add_move_hints(error, &mut err, err_span);
        err.emit();
    }

    fn add_move_hints(
        &self,
        error: GroupedMoveError<'tcx>,
        err: &mut DiagnosticBuilder<'a>,
        span: Span,
    ) {
        match error {
            GroupedMoveError::MovesFromMatchPlace {
                mut binds_to,
                move_from,
                ..
            } => {
                // Ok to suggest a borrow, since the target can't be moved from
                // anyway.
                if let Ok(snippet) = self.tcx.sess.codemap().span_to_snippet(span) {
                    match move_from {
                        Place::Projection(ref proj)
                            if self.suitable_to_remove_deref(proj, &snippet) =>
                        {
                            err.span_suggestion(
                                span,
                                "consider removing this dereference operator",
                                format!("{}", &snippet[1..]),
                            );
                        }
                        _ => {
                            err.span_suggestion(
                                span,
                                "consider using a reference instead",
                                format!("&{}", snippet),
                            );
                        }
                    }

                    binds_to.sort();
                    binds_to.dedup();
                    for local in binds_to {
                        let bind_to = &self.mir.local_decls[local];
                        let binding_span = bind_to.source_info.span;
                        err.span_label(
                            binding_span,
                            format!(
                                "move occurs because {} has type `{}`, \
                                 which does not implement the `Copy` trait",
                                bind_to.name.unwrap(),
                                bind_to.ty
                            ),
                        );
                    }
                }
            }
            GroupedMoveError::MovesFromPattern { mut binds_to, .. } => {
                // Suggest ref, since there might be a move in
                // another match arm
                binds_to.sort();
                binds_to.dedup();
                for local in binds_to {
                    let bind_to = &self.mir.local_decls[local];
                    let binding_span = bind_to.source_info.span;

                    // Suggest ref mut when the user has already written mut.
                    let ref_kind = match bind_to.mutability {
                        Mutability::Not => "ref",
                        Mutability::Mut => "ref mut",
                    };
                    match bind_to.name {
                        Some(name) => {
                            err.span_suggestion(
                                binding_span,
                                "to prevent move, use ref or ref mut",
                                format!("{} {:?}", ref_kind, name),
                            );
                        }
                        None => {
                            err.span_label(
                                span,
                                format!("Local {:?} is not suitable for ref", bind_to),
                            );
                        }
                    }
                }
            }
            // Nothing to suggest.
            GroupedMoveError::OtherIllegalMove { .. } => (),
        }
    }

    fn suitable_to_remove_deref(&self, proj: &PlaceProjection<'tcx>, snippet: &str) -> bool {
        let is_shared_ref = |ty: ty::Ty| match ty.sty {
            ty::TypeVariants::TyRef(.., hir::Mutability::MutImmutable) => true,
            _ => false,
        };

        proj.elem == ProjectionElem::Deref && snippet.starts_with('*') && match proj.base {
            Place::Local(local) => {
                let local_decl = &self.mir.local_decls[local];
                // If this is a temporary, then this could be from an
                // overloaded * operator.
                local_decl.is_user_variable.is_some() && is_shared_ref(local_decl.ty)
            }
            Place::Static(ref st) => is_shared_ref(st.ty),
            Place::Projection(ref proj) => match proj.elem {
                ProjectionElem::Field(_, ty) => is_shared_ref(ty),
                _ => false,
            },
        }
    }
}
<|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.

use deriving::generic::*;
use deriving::generic::ty::*;

use syntax::ast::{MetaItem, Expr, BinOpKind, ItemKind, VariantData};
use syntax::codemap::Span;
use syntax::ext::base::{ExtCtxt, Annotatable};
use syntax::ext::build::AstBuilder;
use syntax::parse::token::InternedString;
use syntax::ptr::P;

fn is_clike_enum(item: &Annotatable) -> bool {
    match *item {
        Annotatable::Item(ref item) => {
            match item.node {
                ItemKind::Enum(ref enum_def, _) => {
                    enum_def.variants.iter().all(|v|
                        if let VariantData::Unit(..) = v.node.data {
                            true
                        } else {
                            false
                        }
                    )
                }
                _ => false,
            }
        }
        _ => false,
    }
}

pub fn expand_deriving_partial_eq(cx: &mut ExtCtxt,
                                  span: Span,
                                  mitem: &MetaItem,
                                  item: &Annotatable,
                                  push: &mut FnMut(Annotatable))
{
    // structures are equal if all fields are equal, and non equal, if
    // any fields are not equal or if the enum variants are different
    fn cs_eq(cx: &mut ExtCtxt, span: Span, substr: &Substructure) -> P<Expr> {
        cs_fold(
            true,  // use foldl
            |cx, span, subexpr, self_f, other_fs| {
                let other_f = match (other_fs.len(), other_fs.get(0)) {
                    (1, Some(o_f)) => o_f,
                    _ => cx.span_bug(span, "not exactly 2 arguments in `derive(PartialEq)`")
                };

                let eq = cx.expr_binary(span, BinOpKind::Eq, self_f, other_f.clone());

                cx.expr_binary(span, BinOpKind::And, subexpr, eq)
            },
            cx.expr_bool(span, true),
            Box::new(|cx, span, _, _| cx.expr_bool(span, false)),
            cx, span, substr)
    }
    fn cs_ne(cx: &mut ExtCtxt, span: Span, substr: &Substructure) -> P<Expr> {
        cs_fold(
            true,  // use foldl
            |cx, span, subexpr, self_f, other_fs| {
                let other_f = match (other_fs.len(), other_fs.get(0)) {
                    (1, Some(o_f)) => o_f,
                    _ => cx.span_bug(span, "not exactly 2 arguments in `derive(PartialEq)`")
                };

                let eq = cx.expr_binary(span, BinOpKind::Ne, self_f, other_f.clone());

                cx.expr_binary(span, BinOpKind::Or, subexpr, eq)
            },
            cx.expr_bool(span, false),
            Box::new(|cx, span, _, _| cx.expr_bool(span, true)),
            cx, span, substr)
    }

    macro_rules! md {
        ($name:expr, $f:ident) => { {
            let inline = cx.meta_word(span, InternedString::new("inline"));
            let attrs = vec!(cx.attribute(span, inline));
            MethodDef {
                name: $name,
                generics: LifetimeBounds::empty(),
                explicit_self: borrowed_explicit_self(),
                args: vec!(borrowed_self()),
                ret_ty: Literal(path_local!(bool)),
                attributes: attrs,
                is_unsafe: false,
                combine_substructure: combine_substructure(Box::new(|a, b, c| {
                    $f(a, b, c)
                }))
            }
        } }
    }

    // avoid defining `ne` if we can
    let mut methods = vec![md!("eq", cs_eq)];
    if !is_clike_enum(item) {
        methods.push(md!("ne", cs_ne));
    }

    let trait_def = TraitDef {
        span: span,
        attributes: Vec::new(),
        path: path_std!(cx, core::cmp::PartialEq),
        additional_bounds: Vec::new(),
        generics: LifetimeBounds::empty(),
        is_unsafe: false,
        methods: methods,
        associated_types: Vec::new(),
    };
    trait_def.expand(cx, mitem, item, push)
}
<commit_msg>derive: Skip PartialEq::ne for any zero-field enum or struct<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.

use deriving::generic::*;
use deriving::generic::ty::*;

use syntax::ast::{MetaItem, Expr, BinOpKind, ItemKind};
use syntax::codemap::Span;
use syntax::ext::base::{ExtCtxt, Annotatable};
use syntax::ext::build::AstBuilder;
use syntax::parse::token::InternedString;
use syntax::ptr::P;

fn is_type_without_fields(item: &Annotatable) -> bool {
    if let Annotatable::Item(ref item) = *item {
        match item.node {
            ItemKind::Enum(ref enum_def, _) => {
                enum_def.variants.iter().all(|v| v.node.data.fields().is_empty())
            }
            ItemKind::Struct(ref variant_data, _) => {
                variant_data.fields().is_empty()
            }
            _ => false
        }
    } else {
        false
    }
}

pub fn expand_deriving_partial_eq(cx: &mut ExtCtxt,
                                  span: Span,
                                  mitem: &MetaItem,
                                  item: &Annotatable,
                                  push: &mut FnMut(Annotatable))
{
    // structures are equal if all fields are equal, and non equal, if
    // any fields are not equal or if the enum variants are different
    fn cs_eq(cx: &mut ExtCtxt, span: Span, substr: &Substructure) -> P<Expr> {
        cs_fold(
            true,  // use foldl
            |cx, span, subexpr, self_f, other_fs| {
                let other_f = match (other_fs.len(), other_fs.get(0)) {
                    (1, Some(o_f)) => o_f,
                    _ => cx.span_bug(span, "not exactly 2 arguments in `derive(PartialEq)`")
                };

                let eq = cx.expr_binary(span, BinOpKind::Eq, self_f, other_f.clone());

                cx.expr_binary(span, BinOpKind::And, subexpr, eq)
            },
            cx.expr_bool(span, true),
            Box::new(|cx, span, _, _| cx.expr_bool(span, false)),
            cx, span, substr)
    }
    fn cs_ne(cx: &mut ExtCtxt, span: Span, substr: &Substructure) -> P<Expr> {
        cs_fold(
            true,  // use foldl
            |cx, span, subexpr, self_f, other_fs| {
                let other_f = match (other_fs.len(), other_fs.get(0)) {
                    (1, Some(o_f)) => o_f,
                    _ => cx.span_bug(span, "not exactly 2 arguments in `derive(PartialEq)`")
                };

                let eq = cx.expr_binary(span, BinOpKind::Ne, self_f, other_f.clone());

                cx.expr_binary(span, BinOpKind::Or, subexpr, eq)
            },
            cx.expr_bool(span, false),
            Box::new(|cx, span, _, _| cx.expr_bool(span, true)),
            cx, span, substr)
    }

    macro_rules! md {
        ($name:expr, $f:ident) => { {
            let inline = cx.meta_word(span, InternedString::new("inline"));
            let attrs = vec!(cx.attribute(span, inline));
            MethodDef {
                name: $name,
                generics: LifetimeBounds::empty(),
                explicit_self: borrowed_explicit_self(),
                args: vec!(borrowed_self()),
                ret_ty: Literal(path_local!(bool)),
                attributes: attrs,
                is_unsafe: false,
                combine_substructure: combine_substructure(Box::new(|a, b, c| {
                    $f(a, b, c)
                }))
            }
        } }
    }

    // avoid defining `ne` if we can
    // c-like enums, enums without any fields and structs without fields
    // can safely define only `eq`.
    let mut methods = vec![md!("eq", cs_eq)];
    if !is_type_without_fields(item) {
        methods.push(md!("ne", cs_ne));
    }

    let trait_def = TraitDef {
        span: span,
        attributes: Vec::new(),
        path: path_std!(cx, core::cmp::PartialEq),
        additional_bounds: Vec::new(),
        generics: LifetimeBounds::empty(),
        is_unsafe: false,
        methods: methods,
        associated_types: Vec::new(),
    };
    trait_def.expand(cx, mitem, item, push)
}
<|endoftext|>


<commit_before><commit_msg>Update slicing syntax<commit_after><|endoftext|>


<commit_before><commit_msg>Fix for new StoreId::new() interface<commit_after><|endoftext|>


<commit_before><commit_msg>Test error for `...` in expressions<commit_after>// Copyright 2017 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.

// compile-flags: -Z parse-only -Z continue-parse-after-error

// Make sure that inclusive ranges with `...` syntax don't parse.

#![feature(inclusive_range_syntax, inclusive_range)]

use std::ops::RangeToInclusive;

fn return_range_to() -> RangeToInclusive<i32> {
    return ...1; //~ERROR `...` syntax cannot be used in expressions
                 //~^HELP  Use `..` if you need an exclusive range (a < b)
                 //~^^HELP or `..=` if you need an inclusive range (a <= b)
}

pub fn main() {
    let x = ...0;    //~ERROR `...` syntax cannot be used in expressions
                     //~^HELP  Use `..` if you need an exclusive range (a < b)
                     //~^^HELP or `..=` if you need an inclusive range (a <= b)

    let x = 5...5;   //~ERROR `...` syntax cannot be used in expressions
                     //~^HELP  Use `..` if you need an exclusive range (a < b)
                     //~^^HELP or `..=` if you need an inclusive range (a <= b)

    for _ in 0...1 {} //~ERROR `...` syntax cannot be used in expressions
                     //~^HELP  Use `..` if you need an exclusive range (a < b)
                     //~^^HELP or `..=` if you need an inclusive range (a <= b)
}

<|endoftext|>


<commit_before><commit_msg>Add regression test for #70155.<commit_after>// check-pass
#![allow(incomplete_features)]
#![feature(const_generics)]

// Regression test for #70155:
// `RangeInclusive` should be usable with const generics

struct S<const R: std::ops::RangeInclusive<usize>>;

const C : S<{ 0 ..= 999 }> = S;

pub fn main() {}
<|endoftext|>


<commit_before><commit_msg>Rollup merge of #75695 - JohnTitor:regression-test, r=Dylan-DPC<commit_after>// build-pass

// Regression test for #72793.
// FIXME: This still shows ICE with `-Zmir-opt-level=2`.

#![feature(type_alias_impl_trait)]

trait T { type Item; }

type Alias<'a> = impl T<Item = &'a ()>;

struct S;
impl<'a> T for &'a S {
    type Item = &'a ();
}

fn filter_positive<'a>() -> Alias<'a> {
    &S
}

fn with_positive(fun: impl Fn(Alias<'_>)) {
    fun(filter_positive());
}

fn main() {
    with_positive(|_| ());
}
<|endoftext|>


<commit_before><commit_msg>Resolves issue #1     - properly create config directory and file if they don't exist     - save defaults to that file after creation. load can then progress<commit_after><|endoftext|>


<commit_before><commit_msg>Add dimension_test<commit_after>#[macro_use]
extern crate yoga;

use yoga::{Direction, Node, Point, Undefined};
use yoga::FlexStyle::*;

#[test]
fn test_wrap_child() {
	let mut root = Node::new();

	let mut root_child_0 = Node::new();

	style!(root_child_0,
		Width(100 pt),
		Height(100 pt)
	);

	root.insert_child(&mut root_child_0, 0);
	root.calculate_layout(Undefined, Undefined, Direction::LTR);

	let root_layout = root.get_layout();
	let child_layout = root_child_0.get_layout();

	assert_eq!(0.0, root_layout.left);
	assert_eq!(0.0, root_layout.top);
	assert_eq!(100.0, root_layout.width);
	assert_eq!(100.0, root_layout.height);

	assert_eq!(0.0, child_layout.left);
	assert_eq!(0.0, child_layout.top);
	assert_eq!(100.0, child_layout.width);
	assert_eq!(100.0, child_layout.height);

	root.calculate_layout(Undefined, Undefined, Direction::RTL);

	let root_layout = root.get_layout();
	let child_layout = root_child_0.get_layout();

	assert_eq!(0.0, root_layout.left);
	assert_eq!(0.0, root_layout.top);
	assert_eq!(100.0, root_layout.width);
	assert_eq!(100.0, root_layout.height);

	assert_eq!(0.0, child_layout.left);
	assert_eq!(0.0, child_layout.top);
	assert_eq!(100.0, child_layout.width);
	assert_eq!(100.0, child_layout.height);
}

#[test]
fn test_wrap_grandchild() {
	let mut root = Node::new();

	let mut root_child_0 = Node::new();

	let mut root_child_0_child_0 = Node::new();

	style!(root_child_0_child_0,
		Width(100 pt),
		Height(100 pt)
	);

	root.insert_child(&mut root_child_0, 0);
	root_child_0.insert_child(&mut root_child_0_child_0, 0);
	root.calculate_layout(Undefined, Undefined, Direction::LTR);

	let root_layout = root.get_layout();
	let child_0_layout = root_child_0.get_layout();
	let child_0_child_0_layout = root_child_0.get_layout();

	assert_eq!(0.0, root_layout.left);
	assert_eq!(0.0, root_layout.top);
	assert_eq!(100.0, root_layout.width);
	assert_eq!(100.0, root_layout.height);

	assert_eq!(0.0, child_0_layout.left);
	assert_eq!(0.0, child_0_layout.top);
	assert_eq!(100.0, child_0_layout.width);
	assert_eq!(100.0, child_0_layout.height);

	assert_eq!(0.0, child_0_child_0_layout.left);
	assert_eq!(0.0, child_0_child_0_layout.top);
	assert_eq!(100.0, child_0_child_0_layout.width);
	assert_eq!(100.0, child_0_child_0_layout.height);

	root.calculate_layout(Undefined, Undefined, Direction::RTL);

	let root_layout = root.get_layout();
	let child_0_layout = root_child_0.get_layout();
	let child_0_child_0_layout = root_child_0.get_layout();

	assert_eq!(0.0, root_layout.left);
	assert_eq!(0.0, root_layout.top);
	assert_eq!(100.0, root_layout.width);
	assert_eq!(100.0, root_layout.height);

	assert_eq!(0.0, child_0_layout.left);
	assert_eq!(0.0, child_0_layout.top);
	assert_eq!(100.0, child_0_layout.width);
	assert_eq!(100.0, child_0_layout.height);

	assert_eq!(0.0, child_0_child_0_layout.left);
	assert_eq!(0.0, child_0_child_0_layout.top);
	assert_eq!(100.0, child_0_child_0_layout.width);
	assert_eq!(100.0, child_0_child_0_layout.height);
}
<|endoftext|>


<commit_before><commit_msg>template for new rust files<commit_after>// This file is part of rust-web/twig
//
// For the copyright and license information, please view the LICENSE
// file that was distributed with this source code.

/// Twig library for rust
///
/// @author NAME <EMAIL>

/////////////
// imports //
/////////////

/////////////
// exports //
/////////////
<|endoftext|>


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

#![sanitizer_runtime]
#![feature(alloc_system)]
#![feature(sanitizer_runtime)]
#![feature(staged_api)]
#![no_std]
#![unstable(feature = "sanitizer_runtime_lib",
            reason = "internal implementation detail of sanitizers",
            issue = "0")]

extern crate alloc_system;

use alloc_system::System;

#[global_allocator]
static ALLOC: System = System;
<commit_msg>[nll] librustc_msan: enable feature(nll) for bootstrap<commit_after>// Copyright 2016 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.

#![sanitizer_runtime]
#![feature(alloc_system)]
#![cfg_attr(not(stage0), feature(nll))]
#![feature(sanitizer_runtime)]
#![feature(staged_api)]
#![no_std]
#![unstable(feature = "sanitizer_runtime_lib",
            reason = "internal implementation detail of sanitizers",
            issue = "0")]

extern crate alloc_system;

use alloc_system::System;

#[global_allocator]
static ALLOC: System = System;
<|endoftext|>


<commit_before><commit_msg>Add rust code for collatz-conjecture case<commit_after>// return Ok(x) where x is the number of steps required to reach 1
pub fn collatz(n: u64) -> Result<u64, &'static str> {
    if n < 1 {
        return Err("Invalid number");
    }

    let mut result = n;
    let mut steps = 0;

    while result != 1 {
        if result % 2 == 0 {
            result /= 2;
        } else {
            result = 3 * result + 1;
        }

        steps += 1;
    }

    Ok(steps)
}
<|endoftext|>


<commit_before><commit_msg>add /launcher to api<commit_after><|endoftext|>