<commit_before>use std::fs::File;
use std::collections::HashMap;
use std::ffi::OsStr;
use std::path::{Path, PathBuf};
use std::default::Default;
use error::Result;
use chrono::{DateTime, FixedOffset, Datelike, Timelike};
use yaml_rust::YamlLoader;
use std::io::Read;
use regex::Regex;
use rss;

use liquid::{Renderable, LiquidOptions, Context, Value};

use pulldown_cmark as cmark;
use liquid;

#[derive(Debug)]
pub struct Document {
    pub path: String,
    // TODO store attributes as liquid values?
    pub attributes: HashMap<String, String>,
    pub content: String,
    pub layout: Option<String>,
    pub is_post: bool,
    pub date: Option<DateTime<FixedOffset>>,
    file_path: String,
    markdown: bool,
}

fn read_file(path: &Path) -> Result<String> {
    let mut file = try!(File::open(path));
    let mut text = String::new();
    try!(file.read_to_string(&mut text));
    Ok(text)
}

/// Formats a user specified custom path, adding custom parameters
/// and "exploding" the URL.
fn format_path(p: &str,
               attributes: &HashMap<String, String>,
               date: &Option<DateTime<FixedOffset>>)
               -> Result<String> {
    let mut p = p.to_owned();

    let time_vars = Regex::new(":(year|month|i_month|day|i_day|short_year|hour|minute|second)")
                        .unwrap();
    if time_vars.is_match(&p) {
        let date = try!(date.ok_or(format!("Can not format file path without a valid date \
                                            ({:?})",
                                           p)));

        p = p.replace(":year", &date.year().to_string());
        p = p.replace(":month", &format!("{:02}", &date.month()));
        p = p.replace(":i_month", &date.month().to_string());
        p = p.replace(":day", &format!("{:02}", &date.day()));
        p = p.replace(":i_day", &date.day().to_string());
        p = p.replace(":hour", &format!("{:02}", &date.hour()));
        p = p.replace(":minute", &format!("{:02}", &date.minute()));
        p = p.replace(":second", &format!("{:02}", &date.second()));
    }

    for (key, val) in attributes {
        p = p.replace(&(String::from(":") + key), val);
    }

    // TODO if title is present inject title slug

    let mut path = Path::new(&p);

    // remove the root prefix (leading slash on unix systems)
    if path.has_root() {
        let mut components = path.components();
        components.next();
        path = components.as_path();
    }

    let mut path_buf = path.to_path_buf();

    // explode the url if no extension was specified
    if path_buf.extension().is_none() {
        path_buf.push("index.html")
    }

    Ok(path_buf.to_string_lossy().into_owned())
}

impl Document {
    pub fn new(path: String,
               attributes: HashMap<String, String>,
               content: String,
               layout: Option<String>,
               is_post: bool,
               date: Option<DateTime<FixedOffset>>,
               file_path: String,
               markdown: bool)
               -> Document {
        Document {
            path: path,
            attributes: attributes,
            content: content,
            layout: layout,
            is_post: is_post,
            date: date,
            file_path: file_path,
            markdown: markdown,
        }
    }

    pub fn parse(file_path: &Path, source: &Path) -> Result<Document> {
        let mut attributes = HashMap::new();
        let mut content = try!(read_file(file_path));

        // if there is front matter, split the file and parse it
        // TODO: make this a regex to support lines of any length
        if content.contains("---") {
            let content2 = content.clone();
            let mut content_splits = content2.split("---");

            // above the split are the attributes
            let attribute_string = content_splits.next().unwrap_or("");

            // everything below the split becomes the new content
            content = content_splits.next().unwrap_or("").to_owned();

            let yaml_result = try!(YamlLoader::load_from_str(attribute_string));

            let yaml_attributes = try!(yaml_result[0]
                                           .as_hash()
                                           .ok_or(format!("Incorrect front matter format in \
                                                           {:?}",
                                                          file_path)));

            for (key, value) in yaml_attributes {
                // TODO store attributes as liquid values
                attributes.insert(key.as_str().unwrap_or("").to_owned(),
                                  value.as_str().unwrap_or("").to_owned());
            }
        }

        let date = attributes.get("date")
                             .and_then(|d| {
                                 DateTime::parse_from_str(d, "%d %B %Y %H:%M:%S %z").ok()
                             });

        // if the file has a .md extension we assume it's markdown
        // TODO add a "markdown" flag to yaml front matter
        let markdown = file_path.extension().unwrap_or(OsStr::new("")) == OsStr::new("md");

        let layout = attributes.get(&"extends".to_owned()).cloned();

        let path_str = try!(file_path.to_str()
                                     .ok_or(format!("Cannot convert pathname {:?} to UTF-8",
                                                    file_path)));

        let source_str = try!(source.to_str()
                                    .ok_or(format!("Cannot convert pathname {:?} to UTF-8",
                                                   source)));

        // construct a relative path to the source
        // TODO: use strip_prefix instead
        let new_path = try!(path_str.split(source_str)
                                    .last()
                                    .ok_or(format!("Empty path")));

        let mut path_buf = PathBuf::from(new_path);
        path_buf.set_extension("html");

        // if the user specified a custom path override
        // format it and push it over the original file name
        if let Some(path) = attributes.get("path") {

            // TODO replace "date", "pretty", "ordinal" and "none"
            // for Jekyl compatibility

            path_buf = if let Some(parent) = path_buf.parent() {
                let mut p = PathBuf::from(parent);
                p.push(try!(format_path(path, &attributes, &date)));
                p
            } else {
                PathBuf::from(try!(format_path(path, &attributes, &date)))
            }
        };

        let path = try!(path_buf.to_str()
                                .ok_or(format!("Cannot convert pathname {:?} to UTF-8", path_buf)));

        Ok(Document::new(path.to_owned(),
                         attributes,
                         content,
                         layout,
                         false,
                         date,
                         file_path.to_string_lossy().into_owned(),
                         markdown))
    }

    /// Metadata for generating RSS feeds
    pub fn to_rss(&self, root_url: &str) -> rss::Item {
        rss::Item {
            title: self.attributes.get("title").map(|s| s.to_owned()),
            link: Some(root_url.to_owned() + &self.path),
            pub_date: self.date.map(|date| date.to_rfc2822()),
            description: self.attributes.get("description").map(|s| s.to_owned()),
            ..Default::default()
        }
    }

    /// Attributes that are injected into the template when rendering
    pub fn get_attributes(&self) -> HashMap<String, Value> {
        let mut data = HashMap::new();

        for (key, val) in &self.attributes {
            data.insert(key.to_owned(), Value::Str(val.clone()));
        }

        // We replace to swap back slashes to forward slashes to ensure the URL's are valid
        data.insert("path".to_owned(), Value::Str(self.path.replace("\\", "/")));

        data.insert("is_post".to_owned(), Value::Bool(self.is_post));

        data
    }

    pub fn as_html(&self,
                   source: &Path,
                   post_data: &Vec<Value>,
                   layouts: &HashMap<String, String>)
                   -> Result<String> {
        let options = LiquidOptions { file_system: Some(source.to_owned()), ..Default::default() };
        let template = try!(liquid::parse(&self.content, options));

        let layout = if let Some(ref layout) = self.layout {
            Some(try!(layouts.get(layout)
                             .ok_or(format!("Layout {} can not be found (defined in {})",
                                            layout,
                                            self.file_path))))
        } else {
            None
        };

        let mut data = Context::with_values(self.get_attributes());
        data.set_val("posts", Value::Array(post_data.clone()));

        let mut html = try!(template.render(&mut data)).unwrap_or(String::new());

        if self.markdown {
            html = {
                let mut buf = String::new();
                let parser = cmark::Parser::new(&html);
                cmark::html::push_html(&mut buf, parser);
                buf
            };
        }

        let options = LiquidOptions { file_system: Some(source.to_owned()), ..Default::default() };

        let template = if let Some(layout) = layout {
            data.set_val("content", Value::Str(html));

            try!(liquid::parse(&layout, options))
        } else {
            try!(liquid::parse(&html, options))
        };

        Ok(try!(template.render(&mut data)).unwrap_or(String::new()))
    }
}
<commit_msg>fix invalid markdown splitting<commit_after>use std::fs::File;
use std::collections::HashMap;
use std::ffi::OsStr;
use std::path::{Path, PathBuf};
use std::default::Default;
use error::Result;
use chrono::{DateTime, FixedOffset, Datelike, Timelike};
use yaml_rust::YamlLoader;
use std::io::Read;
use regex::Regex;
use rss;

use liquid::{Renderable, LiquidOptions, Context, Value};

use pulldown_cmark as cmark;
use liquid;

#[derive(Debug)]
pub struct Document {
    pub path: String,
    // TODO store attributes as liquid values?
    pub attributes: HashMap<String, String>,
    pub content: String,
    pub layout: Option<String>,
    pub is_post: bool,
    pub date: Option<DateTime<FixedOffset>>,
    file_path: String,
    markdown: bool,
}

fn read_file(path: &Path) -> Result<String> {
    let mut file = try!(File::open(path));
    let mut text = String::new();
    try!(file.read_to_string(&mut text));
    Ok(text)
}

/// Formats a user specified custom path, adding custom parameters
/// and "exploding" the URL.
fn format_path(p: &str,
               attributes: &HashMap<String, String>,
               date: &Option<DateTime<FixedOffset>>)
               -> Result<String> {
    let mut p = p.to_owned();

    let time_vars = Regex::new(":(year|month|i_month|day|i_day|short_year|hour|minute|second)")
                        .unwrap();
    if time_vars.is_match(&p) {
        let date = try!(date.ok_or(format!("Can not format file path without a valid date \
                                            ({:?})",
                                           p)));

        p = p.replace(":year", &date.year().to_string());
        p = p.replace(":month", &format!("{:02}", &date.month()));
        p = p.replace(":i_month", &date.month().to_string());
        p = p.replace(":day", &format!("{:02}", &date.day()));
        p = p.replace(":i_day", &date.day().to_string());
        p = p.replace(":hour", &format!("{:02}", &date.hour()));
        p = p.replace(":minute", &format!("{:02}", &date.minute()));
        p = p.replace(":second", &format!("{:02}", &date.second()));
    }

    for (key, val) in attributes {
        p = p.replace(&(String::from(":") + key), val);
    }

    // TODO if title is present inject title slug

    let mut path = Path::new(&p);

    // remove the root prefix (leading slash on unix systems)
    if path.has_root() {
        let mut components = path.components();
        components.next();
        path = components.as_path();
    }

    let mut path_buf = path.to_path_buf();

    // explode the url if no extension was specified
    if path_buf.extension().is_none() {
        path_buf.push("index.html")
    }

    Ok(path_buf.to_string_lossy().into_owned())
}

impl Document {
    pub fn new(path: String,
               attributes: HashMap<String, String>,
               content: String,
               layout: Option<String>,
               is_post: bool,
               date: Option<DateTime<FixedOffset>>,
               file_path: String,
               markdown: bool)
               -> Document {
        Document {
            path: path,
            attributes: attributes,
            content: content,
            layout: layout,
            is_post: is_post,
            date: date,
            file_path: file_path,
            markdown: markdown,
        }
    }

    pub fn parse(file_path: &Path, source: &Path) -> Result<Document> {
        let mut attributes = HashMap::new();
        let mut content = try!(read_file(file_path));

        // if there is front matter, split the file and parse it
        // TODO: make this a regex to support lines of any length
        if content.contains("---") {
            let content2 = content.clone();
            let mut content_splits = content2.splitn(2, "---");

            // above the split are the attributes
            let attribute_string = content_splits.next().unwrap_or("");

            // everything below the split becomes the new content
            content = content_splits.next().unwrap_or("").to_owned();

            let yaml_result = try!(YamlLoader::load_from_str(attribute_string));

            let yaml_attributes = try!(yaml_result[0]
                                           .as_hash()
                                           .ok_or(format!("Incorrect front matter format in \
                                                           {:?}",
                                                          file_path)));

            for (key, value) in yaml_attributes {
                // TODO store attributes as liquid values
                attributes.insert(key.as_str().unwrap_or("").to_owned(),
                                  value.as_str().unwrap_or("").to_owned());
            }
        }

        let date = attributes.get("date")
                             .and_then(|d| {
                                 DateTime::parse_from_str(d, "%d %B %Y %H:%M:%S %z").ok()
                             });

        // if the file has a .md extension we assume it's markdown
        // TODO add a "markdown" flag to yaml front matter
        let markdown = file_path.extension().unwrap_or(OsStr::new("")) == OsStr::new("md");

        let layout = attributes.get(&"extends".to_owned()).cloned();

        let path_str = try!(file_path.to_str()
                                     .ok_or(format!("Cannot convert pathname {:?} to UTF-8",
                                                    file_path)));

        let source_str = try!(source.to_str()
                                    .ok_or(format!("Cannot convert pathname {:?} to UTF-8",
                                                   source)));

        // construct a relative path to the source
        // TODO: use strip_prefix instead
        let new_path = try!(path_str.split(source_str)
                                    .last()
                                    .ok_or(format!("Empty path")));

        let mut path_buf = PathBuf::from(new_path);
        path_buf.set_extension("html");

        // if the user specified a custom path override
        // format it and push it over the original file name
        if let Some(path) = attributes.get("path") {

            // TODO replace "date", "pretty", "ordinal" and "none"
            // for Jekyl compatibility

            path_buf = if let Some(parent) = path_buf.parent() {
                let mut p = PathBuf::from(parent);
                p.push(try!(format_path(path, &attributes, &date)));
                p
            } else {
                PathBuf::from(try!(format_path(path, &attributes, &date)))
            }
        };

        let path = try!(path_buf.to_str()
                                .ok_or(format!("Cannot convert pathname {:?} to UTF-8", path_buf)));

        Ok(Document::new(path.to_owned(),
                         attributes,
                         content,
                         layout,
                         false,
                         date,
                         file_path.to_string_lossy().into_owned(),
                         markdown))
    }

    /// Metadata for generating RSS feeds
    pub fn to_rss(&self, root_url: &str) -> rss::Item {
        rss::Item {
            title: self.attributes.get("title").map(|s| s.to_owned()),
            link: Some(root_url.to_owned() + &self.path),
            pub_date: self.date.map(|date| date.to_rfc2822()),
            description: self.attributes.get("description").map(|s| s.to_owned()),
            ..Default::default()
        }
    }

    /// Attributes that are injected into the template when rendering
    pub fn get_attributes(&self) -> HashMap<String, Value> {
        let mut data = HashMap::new();

        for (key, val) in &self.attributes {
            data.insert(key.to_owned(), Value::Str(val.clone()));
        }

        // We replace to swap back slashes to forward slashes to ensure the URL's are valid
        data.insert("path".to_owned(), Value::Str(self.path.replace("\\", "/")));

        data.insert("is_post".to_owned(), Value::Bool(self.is_post));

        data
    }

    pub fn as_html(&self,
                   source: &Path,
                   post_data: &Vec<Value>,
                   layouts: &HashMap<String, String>)
                   -> Result<String> {
        let options = LiquidOptions { file_system: Some(source.to_owned()), ..Default::default() };
        let template = try!(liquid::parse(&self.content, options));

        let layout = if let Some(ref layout) = self.layout {
            Some(try!(layouts.get(layout)
                             .ok_or(format!("Layout {} can not be found (defined in {})",
                                            layout,
                                            self.file_path))))
        } else {
            None
        };

        let mut data = Context::with_values(self.get_attributes());
        data.set_val("posts", Value::Array(post_data.clone()));

        let mut html = try!(template.render(&mut data)).unwrap_or(String::new());

        if self.markdown {
            html = {
                let mut buf = String::new();
                let parser = cmark::Parser::new(&html);
                cmark::html::push_html(&mut buf, parser);
                buf
            };
        }

        let options = LiquidOptions { file_system: Some(source.to_owned()), ..Default::default() };

        let template = if let Some(layout) = layout {
            data.set_val("content", Value::Str(html));

            try!(liquid::parse(&layout, options))
        } else {
            try!(liquid::parse(&html, options))
        };

        Ok(try!(template.render(&mut data)).unwrap_or(String::new()))
    }
}
<|endoftext|>


<commit_before><commit_msg>Add test for issue #53275<commit_after>// run-pass

#![crate_type = "lib"]
struct S(u8);

pub fn ice() {
    S([][0]);
}
<|endoftext|>


<commit_before><commit_msg>Change ignore_enum_variants parameters<commit_after><|endoftext|>


<commit_before><commit_msg>added Matches to api<commit_after><|endoftext|>


<commit_before>#![feature(macro_rules)]

use std::cmp::Ordering::{Greater, Equal, Less};

pub struct Slide<T: Iterator, A> {
  iter: T,
  n: uint,
  window: Vec
}

macro_rules! return_if(
  ($cond:expr, $value:expr) => (
    if $cond {
      return $value;
    }
  );
);

impl<A: Clone, T: Iterator> Slide<T, A> {
  fn push_window(&mut self) -> bool {
    let iter_next = self.iter.next();
    let is_some = iter_next.is_some();

    if is_some {
      self.window.push(iter_next.unwrap());
    }

    is_some
  }

  fn new(iter: T, n: uint) -> Slide<T, A> {
    Slide{
      iter: iter,
      n: n,
      window: Vec::with_capacity(n + 1)
    }
  }
}

impl<A: Clone, T: Iterator> Iterator<Vec> for Slide<T, A> {
  fn next(&mut self) -> Option<Vec> {
    return_if!(self.n == 0, None);
    return_if!(!self.push_window(), None);

    loop {
      let window_status = self.window.len().cmp(&self.n);

      match window_status {
        Greater => { self.window.remove(0); }
        Equal => { return Some(self.window.clone()); }
        Less => { return_if!(!self.push_window(), None); }
      }
    }
  }
}

pub trait SlideIterator<T: Iterator, A> {
  fn slide(self, n: uint) -> Slide<T, A>;
}

impl<A: Clone, T: Iterator> SlideIterator<T, A> for T {
  fn slide(self, n: uint) -> Slide<T, A> {
    Slide::new(self, n)
  }
}

#[test]
fn test_slide() {
  let mut slide_iter = vec![1i, 2, 3, 4, 5].into_iter().slide(3);
  assert_eq!(slide_iter.next().unwrap(), vec![1, 2, 3]);
  assert_eq!(slide_iter.next().unwrap(), vec![2, 3, 4]);
  assert_eq!(slide_iter.next().unwrap(), vec![3, 4, 5]);
  assert!(slide_iter.next().is_none());
}

#[test]
fn test_slide_equal_window() {
  let mut slide_iter = vec![1i, 2, 3, 4, 5].into_iter().slide(5);
  assert_eq!(slide_iter.next().unwrap(), vec![1, 2, 3, 4, 5]);
  assert!(slide_iter.next().is_none());
}

#[test]
fn test_slide_zero_window() {
  let mut slide_iter = vec![1i, 2, 3, 4, 5].into_iter().slide(0);
  assert!(slide_iter.next().is_none());
}

#[test]
fn test_slide_overlong_window() {
  let mut slide_iter = vec![1i, 2, 3, 4, 5].into_iter().slide(7);
  assert!(slide_iter.next().is_none());
}
<commit_msg>Compiles with most recent rust<commit_after>#![feature(macro_rules)]

use std::cmp::Ordering::{Greater, Equal, Less};

pub struct Slide<T: Iterator<Item=A>, A> {
  iter: T,
  n: usize,
  window: Vec
}

macro_rules! return_if(
  ($cond:expr, $value:expr) => (
    if $cond {
      return $value;
    }
  );
);

impl<A: Clone, T: Iterator<Item=A>> Slide<T, A> {
  fn push_window(&mut self) -> bool {
    let iter_next = self.iter.next();
    let is_some = iter_next.is_some();

    if is_some {
      self.window.push(iter_next.unwrap());
    }

    is_some
  }

  fn new(iter: T, n: usize) -> Slide<T, A> {
    Slide{
      iter: iter,
      n: n,
      window: Vec::with_capacity(n + 1)
    }
  }
}

impl<A: Clone, T: Iterator<Item=A>> Iterator for Slide<T, A> {
  type Item = Vec;

  fn next(&mut self) -> Option<Vec> {
    return_if!(self.n == 0, None);
    return_if!(!self.push_window(), None);

    loop {
      let window_status = self.window.len().cmp(&self.n);

      match window_status {
        Greater => { self.window.remove(0); }
        Equal => { return Some(self.window.clone()); }
        Less => { return_if!(!self.push_window(), None); }
      }
    }
  }
}

pub trait SlideIterator<T: Iterator<Item=A>, A> {
  fn slide(self, n: usize) -> Slide<T, A>;
}

impl<A: Clone, T: Iterator<Item=A>> SlideIterator<T, A> for T {
  fn slide(self, n: usize) -> Slide<T, A> {
    Slide::new(self, n)
  }
}

#[test]
fn test_slide() {
  let mut slide_iter = vec![1i8, 2, 3, 4, 5].into_iter().slide(3);
  assert_eq!(slide_iter.next().unwrap(), vec![1, 2, 3]);
  assert_eq!(slide_iter.next().unwrap(), vec![2, 3, 4]);
  assert_eq!(slide_iter.next().unwrap(), vec![3, 4, 5]);
  assert!(slide_iter.next().is_none());
}

#[test]
fn test_slide_equal_window() {
  let mut slide_iter = vec![1i8, 2, 3, 4, 5].into_iter().slide(5);
  assert_eq!(slide_iter.next().unwrap(), vec![1, 2, 3, 4, 5]);
  assert!(slide_iter.next().is_none());
}

#[test]
fn test_slide_zero_window() {
  let mut slide_iter = vec![1i8, 2, 3, 4, 5].into_iter().slide(0);
  assert!(slide_iter.next().is_none());
}

#[test]
fn test_slide_overlong_window() {
  let mut slide_iter = vec![1i8, 2, 3, 4, 5].into_iter().slide(7);
  assert!(slide_iter.next().is_none());
}
<|endoftext|>


<commit_before><commit_msg>Re-format test<commit_after><|endoftext|>


<commit_before><commit_msg>Switch cfg(windows) to cfg(not(macos || linux))<commit_after><|endoftext|>


<commit_before><commit_msg>Bug fix: Error when pgn files starts with ws<commit_after><|endoftext|>


<commit_before><commit_msg>build: deny missing docs<commit_after><|endoftext|>


<commit_before><commit_msg> change to make all tests run<commit_after><|endoftext|>


<commit_before><commit_msg>Verify JSON via a top level function that delegates to a Verifier.<commit_after><|endoftext|>


<commit_before><commit_msg>Make code more functional by more function chaining<commit_after><|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.

use std::collections::HashSet;

use build::{Build, Compiler};

#[derive(Hash, Eq, PartialEq, Clone, Debug)]
pub struct Step<'a> {
    pub src: Source<'a>,
    pub target: &'a str,
}

macro_rules! targets {
    ($m:ident) => {
        $m! {
            (rustc, Rustc { stage: u32 }),
            (libstd, Libstd { stage: u32, compiler: Compiler<'a> }),
            (librustc, Librustc { stage: u32, compiler: Compiler<'a> }),
            (llvm, Llvm { _dummy: () }),
            (compiler_rt, CompilerRt { _dummy: () }),
        }
    }
}

macro_rules! item { ($a:item) => ($a) }

macro_rules! define_source {
    ($(($short:ident, $name:ident { $($args:tt)* }),)*) => {
        item! {
            #[derive(Hash, Eq, PartialEq, Clone, Debug)]
            pub enum Source<'a> {
                $($name { $($args)* }),*
            }
        }
    }
}

targets!(define_source);

pub fn all(build: &Build) -> Vec<Step> {
    let mut ret = Vec::new();
    let mut all = HashSet::new();
    for target in top_level(build) {
        fill(build, &target, &mut ret, &mut all);
    }
    return ret;

    fn fill<'a>(build: &'a Build,
                target: &Step<'a>,
                ret: &mut Vec<Step<'a>>,
                set: &mut HashSet<Step<'a>>) {
        if set.insert(target.clone()) {
            for dep in target.deps(build) {
                fill(build, &dep, ret, set);
            }
            ret.push(target.clone());
        }
    }
}

fn top_level(build: &Build) -> Vec<Step> {
    let mut targets = Vec::new();
    let stage = build.flags.stage.unwrap_or(2);

    let host = Step {
        src: Source::Llvm { _dummy: () },
        target: build.flags.host.iter().next()
                     .unwrap_or(&build.config.build),
    };
    let target = Step {
        src: Source::Llvm { _dummy: () },
        target: build.flags.target.iter().next().map(|x| &x[..])
                     .unwrap_or(host.target)
    };

    add_steps(build, stage, &host, &target, &mut targets);

    if targets.len() == 0 {
        let t = Step {
            src: Source::Llvm { _dummy: () },
            target: &build.config.build,
        };
        for host in build.config.host.iter() {
            if !build.flags.host.contains(host) {
                continue
            }
            let host = t.target(host);
            targets.push(host.librustc(stage, host.compiler(stage)));
            for target in build.config.target.iter() {
                if !build.flags.target.contains(target) {
                    continue
                }
                targets.push(host.target(target)
                                 .libstd(stage, host.compiler(stage)));
            }
        }
    }

    return targets

}

fn add_steps<'a>(build: &'a Build,
                 stage: u32,
                 host: &Step<'a>,
                 target: &Step<'a>,
                 targets: &mut Vec<Step<'a>>) {
    for step in build.flags.step.iter() {
        let compiler = host.compiler(stage);
        match &step[..] {
            "libstd" => targets.push(target.libstd(stage, compiler)),
            "librustc" => targets.push(target.libstd(stage, compiler)),
            "rustc" => targets.push(host.rustc(stage)),
            "llvm" => targets.push(target.llvm(())),
            "compiler-rt" => targets.push(target.compiler_rt(())),
            _ => panic!("unknown build target: `{}`", step),
        }
    }
}

macro_rules! constructors {
    ($(($short:ident, $name:ident { $($arg:ident: $t:ty),* }),)*) => {$(
        fn $short(&self, $($arg: $t),*) -> Step<'a> {
            Step {
                src: Source::$name { $($arg: $arg),* },
                target: self.target,
            }
        }
    )*}
}

impl<'a> Step<'a> {
    fn compiler(&self, stage: u32) -> Compiler<'a> {
        Compiler::new(stage, self.target)
    }

    fn target(&self, target: &'a str) -> Step<'a> {
        Step { target: target, src: self.src.clone() }
    }

    targets!(constructors);

    pub fn deps(&self, build: &'a Build) -> Vec<Step<'a>> {
        match self.src {
            Source::Rustc { stage: 0 } => {
                if self.target == build.config.build {
                    Vec::new()
                } else {
                    let compiler = Compiler::new(0, &build.config.build);
                    vec![self.librustc(0, compiler)]
                }
            }
            Source::Rustc { stage } => {
                vec![self.librustc(stage - 1, self.compiler(stage - 1))]
            }
            Source::Librustc { stage, compiler } => {
                vec![self.libstd(stage, compiler), self.llvm(())]
            }
            Source::Libstd { stage: _, compiler } => {
                vec![self.compiler_rt(()),
                     self.rustc(compiler.stage).target(compiler.host)]
            }
            Source::CompilerRt { _dummy } => {
                vec![self.llvm(()).target(&build.config.build)]
            }
            Source::Llvm { _dummy } => Vec::new(),
        }
    }
}
<commit_msg>rustbuild: Enable bootstrapping new hosts<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.

use std::collections::HashSet;

use build::{Build, Compiler};

#[derive(Hash, Eq, PartialEq, Clone, Debug)]
pub struct Step<'a> {
    pub src: Source<'a>,
    pub target: &'a str,
}

macro_rules! targets {
    ($m:ident) => {
        $m! {
            (rustc, Rustc { stage: u32 }),
            (libstd, Libstd { stage: u32, compiler: Compiler<'a> }),
            (librustc, Librustc { stage: u32, compiler: Compiler<'a> }),
            (llvm, Llvm { _dummy: () }),
            (compiler_rt, CompilerRt { _dummy: () }),
        }
    }
}

macro_rules! item { ($a:item) => ($a) }

macro_rules! define_source {
    ($(($short:ident, $name:ident { $($args:tt)* }),)*) => {
        item! {
            #[derive(Hash, Eq, PartialEq, Clone, Debug)]
            pub enum Source<'a> {
                $($name { $($args)* }),*
            }
        }
    }
}

targets!(define_source);

pub fn all(build: &Build) -> Vec<Step> {
    let mut ret = Vec::new();
    let mut all = HashSet::new();
    for target in top_level(build) {
        fill(build, &target, &mut ret, &mut all);
    }
    return ret;

    fn fill<'a>(build: &'a Build,
                target: &Step<'a>,
                ret: &mut Vec<Step<'a>>,
                set: &mut HashSet<Step<'a>>) {
        if set.insert(target.clone()) {
            for dep in target.deps(build) {
                fill(build, &dep, ret, set);
            }
            ret.push(target.clone());
        }
    }
}

fn top_level(build: &Build) -> Vec<Step> {
    let mut targets = Vec::new();
    let stage = build.flags.stage.unwrap_or(2);

    let host = Step {
        src: Source::Llvm { _dummy: () },
        target: build.flags.host.iter().next()
                     .unwrap_or(&build.config.build),
    };
    let target = Step {
        src: Source::Llvm { _dummy: () },
        target: build.flags.target.iter().next().map(|x| &x[..])
                     .unwrap_or(host.target)
    };

    add_steps(build, stage, &host, &target, &mut targets);

    if targets.len() == 0 {
        let t = Step {
            src: Source::Llvm { _dummy: () },
            target: &build.config.build,
        };
        for host in build.config.host.iter() {
            if !build.flags.host.contains(host) {
                continue
            }
            let host = t.target(host);
            targets.push(host.librustc(stage, host.compiler(stage)));
            for target in build.config.target.iter() {
                if !build.flags.target.contains(target) {
                    continue
                }
                targets.push(host.target(target)
                                 .libstd(stage, host.compiler(stage)));
            }
        }
    }

    return targets

}

fn add_steps<'a>(build: &'a Build,
                 stage: u32,
                 host: &Step<'a>,
                 target: &Step<'a>,
                 targets: &mut Vec<Step<'a>>) {
    for step in build.flags.step.iter() {
        let compiler = host.compiler(stage);
        match &step[..] {
            "libstd" => targets.push(target.libstd(stage, compiler)),
            "librustc" => targets.push(target.libstd(stage, compiler)),
            "rustc" => targets.push(host.rustc(stage)),
            "llvm" => targets.push(target.llvm(())),
            "compiler-rt" => targets.push(target.compiler_rt(())),
            _ => panic!("unknown build target: `{}`", step),
        }
    }
}

macro_rules! constructors {
    ($(($short:ident, $name:ident { $($arg:ident: $t:ty),* }),)*) => {$(
        fn $short(&self, $($arg: $t),*) -> Step<'a> {
            Step {
                src: Source::$name { $($arg: $arg),* },
                target: self.target,
            }
        }
    )*}
}

impl<'a> Step<'a> {
    fn compiler(&self, stage: u32) -> Compiler<'a> {
        Compiler::new(stage, self.target)
    }

    fn target(&self, target: &'a str) -> Step<'a> {
        Step { target: target, src: self.src.clone() }
    }

    targets!(constructors);

    pub fn deps(&self, build: &'a Build) -> Vec<Step<'a>> {
        match self.src {
            Source::Rustc { stage: 0 } => {
                assert!(self.target == build.config.build);
                Vec::new()
            }
            Source::Rustc { stage } => {
                let compiler = Compiler::new(stage - 1, &build.config.build);
                vec![self.librustc(stage - 1, compiler)]
            }
            Source::Librustc { stage, compiler } => {
                vec![self.libstd(stage, compiler), self.llvm(())]
            }
            Source::Libstd { stage: _, compiler } => {
                vec![self.compiler_rt(()),
                     self.rustc(compiler.stage).target(compiler.host)]
            }
            Source::CompilerRt { _dummy } => {
                vec![self.llvm(()).target(&build.config.build)]
            }
            Source::Llvm { _dummy } => Vec::new(),
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Add NameEvent.<commit_after><|endoftext|>


<commit_before><commit_msg>Handle channel create/update and emojis update<commit_after><|endoftext|>


<commit_before><commit_msg>Whoops, forget to send ui_helpers.rs<commit_after>use pbr::{ProgressBar, Pipe, MultiBar, Units};
use std::io::Stdout;
use std::sync::Mutex;
use std::thread;

lazy_static! {
    static ref PBRS: Mutex<Vec<ProgressBar<Pipe>>> = Mutex::new(vec![]);
}

pub fn start_pbr(file_name: String, lengths: Vec<u64>) {
    let mut mb = MultiBar::new();
    mb.println(&format!("Downloading: {}", file_name));
    mb.println("");

    for length in lengths {
        build_bar(&mut mb, length);
    }

    thread::spawn(move || mb.listen());
}

pub fn update_bar(bar: usize, progress: u64) {
    PBRS.lock().expect("Failed to aquire PBRS lock, lock poisoned!")[bar].set(progress);
}

pub fn success_bar(bar: usize) {
    finish_bar_with_message(bar, "Download Complete!");
}

pub fn fail_bar(bar: usize) {
    finish_bar_with_message(bar, "Download Failed! Retrying.");
}

fn finish_bar_with_message(bar: usize, message: &str) {
    PBRS.lock().expect("Failed to aquire PBRS lock, lock poisoned!")[bar].finish_print(message);
}

fn build_bar(mb: &mut MultiBar<Stdout>, size: u64) {
    let mut pbrs = PBRS.lock().expect("Failed to aquire PBRS lock, lock poisoned!");
    let mut pb = mb.create_bar(size);
    pb.tick_format("▏▎▍▌▋▊▉██▉▊▋▌▍▎▏");
    pb.set_units(Units::Bytes);
    pb.tick();
    pbrs.push(pb);
}
<|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.

#![allow(dead_code, missing_docs, bad_style)]

use io::{self, ErrorKind};

pub mod args;
#[cfg(feature = "backtrace")]
pub mod backtrace;
pub mod condvar;
pub mod env;
pub mod ext;
pub mod fast_thread_local;
pub mod fd;
pub mod fs;
pub mod memchr;
pub mod mutex;
pub mod net;
pub mod os;
pub mod os_str;
pub mod path;
pub mod pipe;
pub mod process;
pub mod rand;
pub mod rwlock;
pub mod stack_overflow;
pub mod stdio;
pub mod syscall;
pub mod thread;
pub mod thread_local;
pub mod time;

#[cfg(not(test))]
pub fn init() {
    use alloc::oom;

    oom::set_oom_handler(oom_handler);

    // A nicer handler for out-of-memory situations than the default one. This
    // one prints a message to stderr before aborting. It is critical that this
    // code does not allocate any memory since we are in an OOM situation. Any
    // errors are ignored while printing since there's nothing we can do about
    // them and we are about to exit anyways.
    fn oom_handler() -> ! {
        use intrinsics;
        let msg = "fatal runtime error: out of memory\n";
        unsafe {
            let _ = syscall::write(2, msg.as_bytes());
            intrinsics::abort();
        }
    }
}

pub fn decode_error_kind(errno: i32) -> ErrorKind {
    match errno {
        syscall::ECONNREFUSED => ErrorKind::ConnectionRefused,
        syscall::ECONNRESET => ErrorKind::ConnectionReset,
        syscall::EPERM | syscall::EACCES => ErrorKind::PermissionDenied,
        syscall::EPIPE => ErrorKind::BrokenPipe,
        syscall::ENOTCONN => ErrorKind::NotConnected,
        syscall::ECONNABORTED => ErrorKind::ConnectionAborted,
        syscall::EADDRNOTAVAIL => ErrorKind::AddrNotAvailable,
        syscall::EADDRINUSE => ErrorKind::AddrInUse,
        syscall::ENOENT => ErrorKind::NotFound,
        syscall::EINTR => ErrorKind::Interrupted,
        syscall::EINVAL => ErrorKind::InvalidInput,
        syscall::ETIMEDOUT => ErrorKind::TimedOut,
        syscall::EEXIST => ErrorKind::AlreadyExists,

        // These two constants can have the same value on some systems,
        // but different values on others, so we can't use a match
        // clause
        x if x == syscall::EAGAIN || x == syscall::EWOULDBLOCK =>
            ErrorKind::WouldBlock,

        _ => ErrorKind::Other,
    }
}

pub fn cvt(result: Result<usize, syscall::Error>) -> io::Result<usize> {
    result.map_err(|err| io::Error::from_raw_os_error(err.errno))
}

/// On Redox, use an illegal instruction to abort
pub unsafe fn abort_internal() -> ! {
    ::core::intrinsics::abort();
}
<commit_msg>Rollup merge of #43203 - jackpot51:patch-2, 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, missing_docs, bad_style)]

use io::{self, ErrorKind};

pub mod args;
#[cfg(feature = "backtrace")]
pub mod backtrace;
pub mod condvar;
pub mod env;
pub mod ext;
pub mod fast_thread_local;
pub mod fd;
pub mod fs;
pub mod memchr;
pub mod mutex;
pub mod net;
pub mod os;
pub mod os_str;
pub mod path;
pub mod pipe;
pub mod process;
pub mod rand;
pub mod rwlock;
pub mod stack_overflow;
pub mod stdio;
pub mod syscall;
pub mod thread;
pub mod thread_local;
pub mod time;

#[cfg(not(test))]
pub fn init() {}

pub fn decode_error_kind(errno: i32) -> ErrorKind {
    match errno {
        syscall::ECONNREFUSED => ErrorKind::ConnectionRefused,
        syscall::ECONNRESET => ErrorKind::ConnectionReset,
        syscall::EPERM | syscall::EACCES => ErrorKind::PermissionDenied,
        syscall::EPIPE => ErrorKind::BrokenPipe,
        syscall::ENOTCONN => ErrorKind::NotConnected,
        syscall::ECONNABORTED => ErrorKind::ConnectionAborted,
        syscall::EADDRNOTAVAIL => ErrorKind::AddrNotAvailable,
        syscall::EADDRINUSE => ErrorKind::AddrInUse,
        syscall::ENOENT => ErrorKind::NotFound,
        syscall::EINTR => ErrorKind::Interrupted,
        syscall::EINVAL => ErrorKind::InvalidInput,
        syscall::ETIMEDOUT => ErrorKind::TimedOut,
        syscall::EEXIST => ErrorKind::AlreadyExists,

        // These two constants can have the same value on some systems,
        // but different values on others, so we can't use a match
        // clause
        x if x == syscall::EAGAIN || x == syscall::EWOULDBLOCK =>
            ErrorKind::WouldBlock,

        _ => ErrorKind::Other,
    }
}

pub fn cvt(result: Result<usize, syscall::Error>) -> io::Result<usize> {
    result.map_err(|err| io::Error::from_raw_os_error(err.errno))
}

/// On Redox, use an illegal instruction to abort
pub unsafe fn abort_internal() -> ! {
    ::core::intrinsics::abort();
}
<|endoftext|>


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

//! Unicode-intensive string manipulations.
//!
//! This module provides functionality to `str` that requires the Unicode
//! methods provided by the unicode parts of the CharExt trait.

use core::char;
use core::iter::{Filter, FusedIterator};
use core::str::Split;

/// An iterator over sub-slices of the original string slice.
///
/// This struct is created by the [`split_whitespace()`] method on [`str`].
/// See its documentation for more.
///
/// [`split_whitespace()`]: ../../std/primitive.str.html#method.split_whitespace
/// [`str`]: ../../std/primitive.str.html
#[stable(feature = "split_whitespace", since = "1.1.0")]
pub struct SplitWhitespace<'a> {
    inner: Filter<Split<'a, fn(char) -> bool>, fn(&&str) -> bool>,
}

/// Methods for Unicode string slices
#[allow(missing_docs)] // docs in libcollections
pub trait UnicodeStr {
    fn split_whitespace<'a>(&'a self) -> SplitWhitespace<'a>;
    fn is_whitespace(&self) -> bool;
    fn is_alphanumeric(&self) -> bool;
    fn trim(&self) -> &str;
    fn trim_left(&self) -> &str;
    fn trim_right(&self) -> &str;
}

impl UnicodeStr for str {
    #[inline]
    fn split_whitespace(&self) -> SplitWhitespace {
        fn is_not_empty(s: &&str) -> bool {
            !s.is_empty()
        }
        let is_not_empty: fn(&&str) -> bool = is_not_empty; // coerce to fn pointer

        fn is_whitespace(c: char) -> bool {
            c.is_whitespace()
        }
        let is_whitespace: fn(char) -> bool = is_whitespace; // coerce to fn pointer

        SplitWhitespace { inner: self.split(is_whitespace).filter(is_not_empty) }
    }

    #[inline]
    fn is_whitespace(&self) -> bool {
        self.chars().all(|c| c.is_whitespace())
    }

    #[inline]
    fn is_alphanumeric(&self) -> bool {
        self.chars().all(|c| c.is_alphanumeric())
    }

    #[inline]
    fn trim(&self) -> &str {
        self.trim_matches(|c: char| c.is_whitespace())
    }

    #[inline]
    fn trim_left(&self) -> &str {
        self.trim_left_matches(|c: char| c.is_whitespace())
    }

    #[inline]
    fn trim_right(&self) -> &str {
        self.trim_right_matches(|c: char| c.is_whitespace())
    }
}

/// Iterator adaptor for encoding `char`s to UTF-16.
#[derive(Clone)]
pub struct Utf16Encoder<I> {
    chars: I,
    extra: u16,
}

impl<I> Utf16Encoder<I> {
    /// Create a UTF-16 encoder from any `char` iterator.
    pub fn new(chars: I) -> Utf16Encoder<I>
        where I: Iterator<Item = char>
    {
        Utf16Encoder {
            chars: chars,
            extra: 0,
        }
    }
}

impl<I> Iterator for Utf16Encoder<I>
    where I: Iterator<Item = char>
{
    type Item = u16;

    #[inline]
    fn next(&mut self) -> Option<u16> {
        if self.extra != 0 {
            let tmp = self.extra;
            self.extra = 0;
            return Some(tmp);
        }

        let mut buf = [0; 2];
        self.chars.next().map(|ch| {
            let n = CharExt::encode_utf16(ch, &mut buf).len();
            if n == 2 {
                self.extra = buf[1];
            }
            buf[0]
        })
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        let (low, high) = self.chars.size_hint();
        // every char gets either one u16 or two u16,
        // so this iterator is between 1 or 2 times as
        // long as the underlying iterator.
        (low, high.and_then(|n| n.checked_mul(2)))
    }
}

#[unstable(feature = "fused", issue = "35602")]
impl<I> FusedIterator for Utf16Encoder<I>
    where I: FusedIterator<Item = char> {}

#[stable(feature = "split_whitespace", since = "1.1.0")]
impl<'a> Iterator for SplitWhitespace<'a> {
    type Item = &'a str;

    fn next(&mut self) -> Option<&'a str> {
        self.inner.next()
    }
}

#[stable(feature = "split_whitespace", since = "1.1.0")]
impl<'a> DoubleEndedIterator for SplitWhitespace<'a> {
    fn next_back(&mut self) -> Option<&'a str> {
        self.inner.next_back()
    }
}

#[unstable(feature = "fused", issue = "35602")]
impl<'a> FusedIterator for SplitWhitespace<'a> {}
<commit_msg>Revert SplitWhitespace's description<commit_after>// Copyright 2012-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.

//! Unicode-intensive string manipulations.
//!
//! This module provides functionality to `str` that requires the Unicode
//! methods provided by the unicode parts of the CharExt trait.

use core::char;
use core::iter::{Filter, FusedIterator};
use core::str::Split;

/// An iterator over the non-whitespace substrings of a string,
/// separated by any amount of whitespace.
///
/// This struct is created by the [`split_whitespace()`] method on [`str`].
/// See its documentation for more.
///
/// [`split_whitespace()`]: ../../std/primitive.str.html#method.split_whitespace
/// [`str`]: ../../std/primitive.str.html
#[stable(feature = "split_whitespace", since = "1.1.0")]
pub struct SplitWhitespace<'a> {
    inner: Filter<Split<'a, fn(char) -> bool>, fn(&&str) -> bool>,
}

/// Methods for Unicode string slices
#[allow(missing_docs)] // docs in libcollections
pub trait UnicodeStr {
    fn split_whitespace<'a>(&'a self) -> SplitWhitespace<'a>;
    fn is_whitespace(&self) -> bool;
    fn is_alphanumeric(&self) -> bool;
    fn trim(&self) -> &str;
    fn trim_left(&self) -> &str;
    fn trim_right(&self) -> &str;
}

impl UnicodeStr for str {
    #[inline]
    fn split_whitespace(&self) -> SplitWhitespace {
        fn is_not_empty(s: &&str) -> bool {
            !s.is_empty()
        }
        let is_not_empty: fn(&&str) -> bool = is_not_empty; // coerce to fn pointer

        fn is_whitespace(c: char) -> bool {
            c.is_whitespace()
        }
        let is_whitespace: fn(char) -> bool = is_whitespace; // coerce to fn pointer

        SplitWhitespace { inner: self.split(is_whitespace).filter(is_not_empty) }
    }

    #[inline]
    fn is_whitespace(&self) -> bool {
        self.chars().all(|c| c.is_whitespace())
    }

    #[inline]
    fn is_alphanumeric(&self) -> bool {
        self.chars().all(|c| c.is_alphanumeric())
    }

    #[inline]
    fn trim(&self) -> &str {
        self.trim_matches(|c: char| c.is_whitespace())
    }

    #[inline]
    fn trim_left(&self) -> &str {
        self.trim_left_matches(|c: char| c.is_whitespace())
    }

    #[inline]
    fn trim_right(&self) -> &str {
        self.trim_right_matches(|c: char| c.is_whitespace())
    }
}

/// Iterator adaptor for encoding `char`s to UTF-16.
#[derive(Clone)]
pub struct Utf16Encoder<I> {
    chars: I,
    extra: u16,
}

impl<I> Utf16Encoder<I> {
    /// Create a UTF-16 encoder from any `char` iterator.
    pub fn new(chars: I) -> Utf16Encoder<I>
        where I: Iterator<Item = char>
    {
        Utf16Encoder {
            chars: chars,
            extra: 0,
        }
    }
}

impl<I> Iterator for Utf16Encoder<I>
    where I: Iterator<Item = char>
{
    type Item = u16;

    #[inline]
    fn next(&mut self) -> Option<u16> {
        if self.extra != 0 {
            let tmp = self.extra;
            self.extra = 0;
            return Some(tmp);
        }

        let mut buf = [0; 2];
        self.chars.next().map(|ch| {
            let n = CharExt::encode_utf16(ch, &mut buf).len();
            if n == 2 {
                self.extra = buf[1];
            }
            buf[0]
        })
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        let (low, high) = self.chars.size_hint();
        // every char gets either one u16 or two u16,
        // so this iterator is between 1 or 2 times as
        // long as the underlying iterator.
        (low, high.and_then(|n| n.checked_mul(2)))
    }
}

#[unstable(feature = "fused", issue = "35602")]
impl<I> FusedIterator for Utf16Encoder<I>
    where I: FusedIterator<Item = char> {}

#[stable(feature = "split_whitespace", since = "1.1.0")]
impl<'a> Iterator for SplitWhitespace<'a> {
    type Item = &'a str;

    fn next(&mut self) -> Option<&'a str> {
        self.inner.next()
    }
}

#[stable(feature = "split_whitespace", since = "1.1.0")]
impl<'a> DoubleEndedIterator for SplitWhitespace<'a> {
    fn next_back(&mut self) -> Option<&'a str> {
        self.inner.next_back()
    }
}

#[unstable(feature = "fused", issue = "35602")]
impl<'a> FusedIterator for SplitWhitespace<'a> {}
<|endoftext|>


<commit_before><commit_msg>(fix) TcpListener::bind has new arguments.<commit_after><|endoftext|>


<commit_before>#![feature(globs)]

extern crate libc;
extern crate neovim;
extern crate rgtk;
extern crate serialize;

use neovim::nvim_main;
use rgtk::*;
use std::collections::HashSet;
use std::{io, str, time};

mod projects;
mod ui;
mod utils;

mod ffi {
    pub use libc::{c_int, c_uchar, c_void};
    pub use libc::funcs::posix88::unistd::{close, pipe, read, write};
    pub use libc::types::os::arch::c95::size_t;

    extern "C" {
        pub fn fork () -> c_int;
        pub fn kill (pid: c_int, sig: c_int);
    }
}

fn gui_main(
    pty: &mut gtk::VtePty,
    read_fd: ffi::c_int,
    write_fd: ffi::c_int,
    pid: ffi::c_int)
{
    gtk::init();

    // constants

    let width = 1242;
    let height = 768;
    let editor_height = ((height as f32) * 0.75) as i32;

    // create the window

    let title = format!("SolidOak {}.{}.{}",
                        option_env!("CARGO_PKG_VERSION_MAJOR").unwrap(),
                        option_env!("CARGO_PKG_VERSION_MINOR").unwrap(),
                        option_env!("CARGO_PKG_VERSION_PATCH").unwrap());
    let mut window = gtk::Window::new(gtk::WindowType::TopLevel).unwrap();
    window.set_title(title.as_slice());
    window.set_window_position(gtk::WindowPosition::Center);
    window.set_default_size(width, height);

    window.connect(gtk::signals::DeleteEvent::new(|_| {
        unsafe {
            ffi::close(read_fd);
            ffi::close(write_fd);
            ffi::kill(pid, 15);
        }
        gtk::main_quit();
        true
    }));

    // create the panes

    let new_button = gtk::Button::new_with_label("New Project").unwrap();
    let import_button = gtk::Button::new_with_label("Import").unwrap();
    let rename_button = gtk::Button::new_with_label("Rename").unwrap();
    let remove_button = gtk::Button::new_with_label("Remove").unwrap();

    let mut project_buttons = gtk::Box::new(gtk::Orientation::Horizontal, 0).unwrap();
    project_buttons.set_size_request(-1, -1);
    project_buttons.add(&new_button);
    project_buttons.add(&import_button);
    project_buttons.add(&rename_button);
    project_buttons.add(&remove_button);

    let mut project_tree = gtk::TreeView::new().unwrap();
    let selection = project_tree.get_selection().unwrap();
    let column_types = [glib::ffi::g_type_string, glib::ffi::g_type_string];
    let store = gtk::TreeStore::new(&column_types).unwrap();
    let model = store.get_model().unwrap();
    project_tree.set_model(&model);
    project_tree.set_headers_visible(false);

    let mut scroll_pane = gtk::ScrolledWindow::new(None, None).unwrap();
    scroll_pane.add(&project_tree);

    let column = gtk::TreeViewColumn::new().unwrap();
    let cell = gtk::CellRendererText::new().unwrap();
    column.pack_start(&cell, true);
    column.add_attribute(&cell, "text", 0);
    project_tree.append_column(&column);

    let mut project_pane = gtk::Box::new(gtk::Orientation::Vertical, 0).unwrap();
    project_pane.set_size_request(-1, -1);
    project_pane.pack_start(&project_buttons, false, true, 0);
    project_pane.pack_start(&scroll_pane, true, true, 0);

    let mut editor_pane = gtk::VteTerminal::new().unwrap();
    editor_pane.set_size_request(-1, editor_height);
    editor_pane.set_pty(pty);
    editor_pane.watch_child(pid);

    let run_button = gtk::Button::new_with_label("Run").unwrap();
    let build_button = gtk::Button::new_with_label("Build").unwrap();
    let test_button = gtk::Button::new_with_label("Test").unwrap();
    let clean_button = gtk::Button::new_with_label("Clean").unwrap();
    let stop_button = gtk::Button::new_with_label("Stop").unwrap();

    let mut build_buttons = gtk::Box::new(gtk::Orientation::Horizontal, 0).unwrap();
    build_buttons.set_size_request(-1, -1);
    build_buttons.add(&run_button);
    build_buttons.add(&build_button);
    build_buttons.add(&test_button);
    build_buttons.add(&clean_button);
    build_buttons.add(&stop_button);

    let build_term = gtk::VteTerminal::new().unwrap();

    let mut build_pane = gtk::Box::new(gtk::Orientation::Vertical, 0).unwrap();
    build_pane.pack_start(&build_buttons, false, true, 0);
    build_pane.pack_start(&build_term, true, true, 0);

    let mut content = gtk::Box::new(gtk::Orientation::Vertical, 0).unwrap();
    content.pack_start(&editor_pane, false, true, 0);
    content.pack_start(&build_pane, true, true, 0);

    let mut hbox = gtk::Box::new(gtk::Orientation::Horizontal, 0).unwrap();
    hbox.pack_start(&project_pane, false, true, 0);
    hbox.pack_start(&content, true, true, 0);
    window.add(&hbox);

    // populate the project tree

    let mut state = ::utils::State{
        projects: HashSet::new(),
        expansions: HashSet::new(),
        selection: None,
        tree_model: &model,
        tree_store: &store,
        tree_selection: &selection,
        rename_button: &rename_button,
        remove_button: &remove_button,
    };

    ::utils::create_data_dir();
    ::utils::read_prefs(&mut state);
    ::ui::update_project_tree(&mut state, &mut project_tree);

    // connect to the signals

    new_button.connect(gtk::signals::Clicked::new(|| {
        ::projects::new_project(&mut state, &mut project_tree);
    }));
    import_button.connect(gtk::signals::Clicked::new(|| {
        ::projects::import_project(&mut state, &mut project_tree);
    }));
    rename_button.connect(gtk::signals::Clicked::new(|| {
        ::projects::rename_file(&mut state);
    }));
    remove_button.connect(gtk::signals::Clicked::new(|| {
        ::projects::remove_item(&mut state);
    }));
    selection.connect(gtk::signals::Changed::new(|| {
        ::projects::save_selection(&mut state);
    }));
    project_tree.connect(gtk::signals::RowCollapsed::new(|iter_raw, _| {
        let iter = gtk::TreeIter::wrap_pointer(iter_raw);
        ::projects::remove_expansion(&mut state, &iter);
    }));
    project_tree.connect(gtk::signals::RowExpanded::new(|iter_raw, _| {
        let iter = gtk::TreeIter::wrap_pointer(iter_raw);
        ::projects::add_expansion(&mut state, &iter);
    }));

    // show the window

    window.show_all();
    gtk::main();
}

fn main() {
    // takes care of piping stdin/stdout between the gui and nvim
    let mut pty = gtk::VtePty::new().unwrap();

    // two pairs of anonymous pipes for msgpack-rpc between the gui and nvim
    let mut nvim_from_gui : [ffi::c_int, ..2] = [0, ..2];
    let mut gui_from_nvim : [ffi::c_int, ..2] = [0, ..2];
    unsafe {
        ffi::pipe(nvim_from_gui.as_mut_ptr());
        ffi::pipe(gui_from_nvim.as_mut_ptr());
    };

    // split into two processes
    let pid = unsafe { ffi::fork() };

    if pid > 0 { // the gui process
        // listen for messages from nvim
        spawn(proc() {
            let mut buf : [ffi::c_uchar, ..100] = [0, ..100];
            unsafe {
                loop {
                    let buf_ptr = buf.as_mut_ptr() as *mut ffi::c_void;
                    let n = ffi::read(gui_from_nvim[0], buf_ptr, 100);
                    if n < 0 {
                        break;
                    } else if n > 0 {
                        let msg = str::from_utf8(buf.slice_to(n as uint)).unwrap();
                        println!("Received: {}", msg);
                    }
                }
            }
        });

        // start the gui
        gui_main(&mut pty, gui_from_nvim[0], gui_from_nvim[1], pid);
    } else { // the nvim process
        // prepare this process to be piped into the gui
        pty.child_setup();

        // listen for messages from the gui
        spawn(proc() {
            io::timer::sleep(time::Duration::seconds(1));

            let mut ch = neovim::Channel::new(nvim_from_gui[0], gui_from_nvim[1]);
            ch.subscribe("test");

            unsafe {
                let msg = "Hello, world!";
                let msg_c = msg.to_c_str();
                let msg_ptr = msg_c.as_ptr() as *const ffi::c_void;
                ffi::write(gui_from_nvim[1], msg_ptr, msg_c.len() as ffi::size_t);
            }
        });

        // start nvim
        nvim_main();
    }
}
<commit_msg>Pass args to nvim_main<commit_after>#![feature(globs)]

extern crate libc;
extern crate neovim;
extern crate rgtk;
extern crate serialize;

use neovim::nvim_main;
use rgtk::*;
use std::collections::HashSet;
use std::{io, str, time};

mod projects;
mod ui;
mod utils;

mod ffi {
    pub use libc::{c_int, c_uchar, c_void};
    pub use libc::funcs::posix88::unistd::{close, pipe, read, write};
    pub use libc::types::os::arch::c95::size_t;

    extern "C" {
        pub fn fork () -> c_int;
        pub fn kill (pid: c_int, sig: c_int);
    }
}

fn gui_main(
    pty: &mut gtk::VtePty,
    read_fd: ffi::c_int,
    write_fd: ffi::c_int,
    pid: ffi::c_int)
{
    gtk::init();

    // constants

    let width = 1242;
    let height = 768;
    let editor_height = ((height as f32) * 0.75) as i32;

    // create the window

    let title = format!("SolidOak {}.{}.{}",
                        option_env!("CARGO_PKG_VERSION_MAJOR").unwrap(),
                        option_env!("CARGO_PKG_VERSION_MINOR").unwrap(),
                        option_env!("CARGO_PKG_VERSION_PATCH").unwrap());
    let mut window = gtk::Window::new(gtk::WindowType::TopLevel).unwrap();
    window.set_title(title.as_slice());
    window.set_window_position(gtk::WindowPosition::Center);
    window.set_default_size(width, height);

    window.connect(gtk::signals::DeleteEvent::new(|_| {
        unsafe {
            ffi::close(read_fd);
            ffi::close(write_fd);
            ffi::kill(pid, 15);
        }
        gtk::main_quit();
        true
    }));

    // create the panes

    let new_button = gtk::Button::new_with_label("New Project").unwrap();
    let import_button = gtk::Button::new_with_label("Import").unwrap();
    let rename_button = gtk::Button::new_with_label("Rename").unwrap();
    let remove_button = gtk::Button::new_with_label("Remove").unwrap();

    let mut project_buttons = gtk::Box::new(gtk::Orientation::Horizontal, 0).unwrap();
    project_buttons.set_size_request(-1, -1);
    project_buttons.add(&new_button);
    project_buttons.add(&import_button);
    project_buttons.add(&rename_button);
    project_buttons.add(&remove_button);

    let mut project_tree = gtk::TreeView::new().unwrap();
    let selection = project_tree.get_selection().unwrap();
    let column_types = [glib::ffi::g_type_string, glib::ffi::g_type_string];
    let store = gtk::TreeStore::new(&column_types).unwrap();
    let model = store.get_model().unwrap();
    project_tree.set_model(&model);
    project_tree.set_headers_visible(false);

    let mut scroll_pane = gtk::ScrolledWindow::new(None, None).unwrap();
    scroll_pane.add(&project_tree);

    let column = gtk::TreeViewColumn::new().unwrap();
    let cell = gtk::CellRendererText::new().unwrap();
    column.pack_start(&cell, true);
    column.add_attribute(&cell, "text", 0);
    project_tree.append_column(&column);

    let mut project_pane = gtk::Box::new(gtk::Orientation::Vertical, 0).unwrap();
    project_pane.set_size_request(-1, -1);
    project_pane.pack_start(&project_buttons, false, true, 0);
    project_pane.pack_start(&scroll_pane, true, true, 0);

    let mut editor_pane = gtk::VteTerminal::new().unwrap();
    editor_pane.set_size_request(-1, editor_height);
    editor_pane.set_pty(pty);
    editor_pane.watch_child(pid);

    let run_button = gtk::Button::new_with_label("Run").unwrap();
    let build_button = gtk::Button::new_with_label("Build").unwrap();
    let test_button = gtk::Button::new_with_label("Test").unwrap();
    let clean_button = gtk::Button::new_with_label("Clean").unwrap();
    let stop_button = gtk::Button::new_with_label("Stop").unwrap();

    let mut build_buttons = gtk::Box::new(gtk::Orientation::Horizontal, 0).unwrap();
    build_buttons.set_size_request(-1, -1);
    build_buttons.add(&run_button);
    build_buttons.add(&build_button);
    build_buttons.add(&test_button);
    build_buttons.add(&clean_button);
    build_buttons.add(&stop_button);

    let build_term = gtk::VteTerminal::new().unwrap();

    let mut build_pane = gtk::Box::new(gtk::Orientation::Vertical, 0).unwrap();
    build_pane.pack_start(&build_buttons, false, true, 0);
    build_pane.pack_start(&build_term, true, true, 0);

    let mut content = gtk::Box::new(gtk::Orientation::Vertical, 0).unwrap();
    content.pack_start(&editor_pane, false, true, 0);
    content.pack_start(&build_pane, true, true, 0);

    let mut hbox = gtk::Box::new(gtk::Orientation::Horizontal, 0).unwrap();
    hbox.pack_start(&project_pane, false, true, 0);
    hbox.pack_start(&content, true, true, 0);
    window.add(&hbox);

    // populate the project tree

    let mut state = ::utils::State{
        projects: HashSet::new(),
        expansions: HashSet::new(),
        selection: None,
        tree_model: &model,
        tree_store: &store,
        tree_selection: &selection,
        rename_button: &rename_button,
        remove_button: &remove_button,
    };

    ::utils::create_data_dir();
    ::utils::read_prefs(&mut state);
    ::ui::update_project_tree(&mut state, &mut project_tree);

    // connect to the signals

    new_button.connect(gtk::signals::Clicked::new(|| {
        ::projects::new_project(&mut state, &mut project_tree);
    }));
    import_button.connect(gtk::signals::Clicked::new(|| {
        ::projects::import_project(&mut state, &mut project_tree);
    }));
    rename_button.connect(gtk::signals::Clicked::new(|| {
        ::projects::rename_file(&mut state);
    }));
    remove_button.connect(gtk::signals::Clicked::new(|| {
        ::projects::remove_item(&mut state);
    }));
    selection.connect(gtk::signals::Changed::new(|| {
        ::projects::save_selection(&mut state);
    }));
    project_tree.connect(gtk::signals::RowCollapsed::new(|iter_raw, _| {
        let iter = gtk::TreeIter::wrap_pointer(iter_raw);
        ::projects::remove_expansion(&mut state, &iter);
    }));
    project_tree.connect(gtk::signals::RowExpanded::new(|iter_raw, _| {
        let iter = gtk::TreeIter::wrap_pointer(iter_raw);
        ::projects::add_expansion(&mut state, &iter);
    }));

    // show the window

    window.show_all();
    gtk::main();
}

fn main() {
    // takes care of piping stdin/stdout between the gui and nvim
    let mut pty = gtk::VtePty::new().unwrap();

    // two pairs of anonymous pipes for msgpack-rpc between the gui and nvim
    let mut nvim_from_gui : [ffi::c_int, ..2] = [0, ..2];
    let mut gui_from_nvim : [ffi::c_int, ..2] = [0, ..2];
    unsafe {
        ffi::pipe(nvim_from_gui.as_mut_ptr());
        ffi::pipe(gui_from_nvim.as_mut_ptr());
    };

    // split into two processes
    let pid = unsafe { ffi::fork() };

    if pid > 0 { // the gui process
        // listen for messages from nvim
        spawn(proc() {
            let mut buf : [ffi::c_uchar, ..100] = [0, ..100];
            unsafe {
                loop {
                    let buf_ptr = buf.as_mut_ptr() as *mut ffi::c_void;
                    let n = ffi::read(gui_from_nvim[0], buf_ptr, 100);
                    if n < 0 {
                        break;
                    } else if n > 0 {
                        let msg = str::from_utf8(buf.slice_to(n as uint)).unwrap();
                        println!("Received: {}", msg);
                    }
                }
            }
        });

        // start the gui
        gui_main(&mut pty, gui_from_nvim[0], gui_from_nvim[1], pid);
    } else { // the nvim process
        // prepare this process to be piped into the gui
        pty.child_setup();

        // listen for messages from the gui
        spawn(proc() {
            io::timer::sleep(time::Duration::seconds(1));

            let mut ch = neovim::Channel::new(nvim_from_gui[0], gui_from_nvim[1]);
            ch.subscribe("test");

            unsafe {
                let msg = "Hello, world!";
                let msg_c = msg.to_c_str();
                let msg_ptr = msg_c.as_ptr() as *const ffi::c_void;
                ffi::write(gui_from_nvim[1], msg_ptr, msg_c.len() as ffi::size_t);
            }
        });

        // start nvim
        nvim_main(&["nvim"]);
    }
}
<|endoftext|>


<commit_before><commit_msg>clippy lints<commit_after><|endoftext|>


<commit_before><commit_msg>Polish and checks<commit_after><|endoftext|>


<commit_before><commit_msg>Create a driving main function<commit_after><|endoftext|>


<commit_before><commit_msg>adding liquid templating structs<commit_after><|endoftext|>


<commit_before><commit_msg>Improved handling of commands<commit_after><|endoftext|>


<commit_before><commit_msg>First impl<commit_after><|endoftext|>


<commit_before><commit_msg>Swap the Home and End keys that modify the tessellation shader LOD factor<commit_after><|endoftext|>


<commit_before><commit_msg>Architecture parsing & tests<commit_after>//use std::string;

mod architecture {

    #[deriving(PartialEq, Show)]
    enum Error {
        UnknownAlias (String),
        InvalidArchitecture (String),
        InvalidSystem (String),
        InvalidVendor (String),
        InvalidCpu (String)
    }

   #[deriving(PartialEq, Show)]
   enum System {
        AnySystem,
        Linux,
        Windows,
        Darwin,
        CustomSystem (String)
    }

    #[deriving(PartialEq, Show)]
    enum Vendor {
        AnyVendor,
        Vendor (String)
    }

    #[deriving(PartialEq, Show)]
    enum Cpu {
        AnyCpu,
        I386,
        AMD64,
        CustomCpu (String)
    }

    #[deriving(PartialEq, Show)]
    struct Architecture {
        system: System,
        vendor: Vendor,
        cpu: Cpu
    }

    fn parse_alias(a: &str) -> Result<Architecture, Error> {
        match a {
            "any" => Ok(Architecture{ system: AnySystem, vendor: AnyVendor, cpu: AnyCpu }),
            "win32" => Ok(Architecture{ system: Windows, vendor: AnyVendor, cpu: I386 }),
            "win64" => Ok(Architecture{ system: Windows, vendor: AnyVendor, cpu: AMD64 }),
            _ => Err(UnknownAlias(String::from_str(a)))
        }
    }

    fn parse_system(a: &str) -> Result<System, Error> {
        match a {
            "any" => Ok(AnySystem),
            "mswindows"  => Ok(Windows),
            "linux" => Ok(Linux),
            "darwin" => Ok(Darwin),
            "" => Err(InvalidSystem(String::from_str(a))),
            _ => Ok(CustomSystem(String::from_str(a)))
        }
    }

    fn parse_cpu(a: &str) -> Result<Cpu, Error> {
        match a {
            "any" => Ok(AnyCpu),
            "i386" => Ok(I386),
            "amd64" => Ok(AMD64),
            "" => Err(InvalidCpu(String::from_str(a))), // invalid
            _ => Ok(CustomCpu(String::from_str(a)))
        }
    }

    #[test]
    fn empty_cpu_is_an_error() {
        assert!(parse_cpu("") == Err(InvalidCpu(String::from_str(""))))
    }

    #[test]
    fn any_cpu_is_a_special_case() {
        assert!(parse_cpu("any") == Ok(AnyCpu))
    }

    fn parse_vendor(a: &str) -> Result<Vendor, Error> {
        match a {
            "any" => Ok(AnyVendor),
            "" => Err(InvalidVendor(String::from_str(a))), // Invalid
            v => Ok(Vendor(String::from_str(v)))
        }
    }

    #[test]
    fn empty_vendor_is_an_error() {
        assert!(parse_vendor("") == Err(InvalidVendor(String::from_str(""))));
    }

    #[test]
    // make sure the vendor "any" resolves to AnyVendor (as opposed to Vendor("any"))
    fn any_vendor_is_a_special_case() {
        let result = parse_vendor("any");
        assert!(result.is_ok());
        assert!(result == Ok(AnyVendor));
    }

    /**
     * Parses a string describing an archtecture into an architecture struct.
     */
    fn parse_arch(a: &str) -> Result<Architecture, Error> {
        if a == "" {
            Err(InvalidArchitecture(String::from_str(a)))
        }
        else {
            let part_strings : Vec<&str> = a.split('-').collect();
            let parts = part_strings.as_slice();
            match parts.len() {
                1 => parse_alias(parts[0]),
                n @ 2 .. 3 => {
                    let system = try!(parse_system(parts[0]));
                    let cpu = try!(parse_cpu(parts[parts.len()-1]));
                    let vendor_name = if n == 2 { "any" } else { parts[1] };
                    let vendor = try!(parse_vendor(vendor_name));
                    Ok( Architecture {system: system, vendor: vendor, cpu: cpu} )
                }

                _ => Err(InvalidArchitecture(String::from_str(a)))
            }
        }
    }

    #[test]
    fn parse_any() {
        let expected = Architecture { system: AnySystem, vendor: AnyVendor, cpu: AnyCpu };
        assert!(parse_arch("any") == Ok(expected));
    }

    #[test]
    fn empty_string_is_invalid_architecture() {
        let arch = parse_arch("");
        assert!(arch == Err(InvalidArchitecture(String::from_str(""))));
    }

    #[test]
    fn too_many_parts_makes_an_architecture_invalid() {
        let text = "mswindows-somevendor-somerubish-i386";
        let arch = parse_arch(text);
        print!("arch: {}\n", arch);
        assert!(arch == Err(InvalidArchitecture(String::from_str(text))));
    }

    #[test]
    fn parse_windows_no_vendor() {
        let expected = Architecture {system: Windows, vendor: AnyVendor, cpu: I386};
        let result = parse_arch("mswindows-i386");
        assert!(result.is_ok());
        assert!(result == Ok(expected));
    }

    #[test]
    fn parse_windows_with_vendor() {
        let expected = Architecture {
            system: Windows,
            vendor: Vendor(String::from_str("somevendor")),
            cpu: I386
        };
        let result = parse_arch("mswindows-somevendor-i386");
        assert!(result.is_ok());
        assert!(result == Ok(expected));
    }

    #[test]
    fn parse_windows_64() {
        let expected = Architecture {
            system: Windows,
            vendor: AnyVendor,
            cpu: AMD64
        };
        let result = parse_arch("mswindows-amd64");
        assert!(result.is_ok());
        assert!(result == Ok(expected));
    }

    #[test]
    fn empty_system_is_an_error() {
        let a = parse_arch("-i386");
        assert!(a == Err(InvalidSystem(String::from_str(""))));
    }
}

mod version {

}

fn main() {

}<|endoftext|>


<commit_before><commit_msg>Make a vector and fill it with some values<commit_after><|endoftext|>


<commit_before><commit_msg>Test(util): fix test broken by filename change<commit_after><|endoftext|>


<commit_before><commit_msg>make some api pub<commit_after><|endoftext|>


<commit_before>use libc;
use platform;
use std::ptr;
use std::os::{errno, page_size, MemoryMap, MapReadable, MapWritable,
              MapNonStandardFlags};

const STACK_FLAGS: libc::c_int = libc::MAP_STACK
                               | libc::MAP_PRIVATE
                               | libc::MAP_ANON;

pub enum Stack {
  Native {
    sp_limit: *const u8
  },
  Managed {
    buf: MemoryMap,
    valgrind_id: libc::c_uint
  }
}

impl Stack {
  pub fn new(size: uint) -> Stack {
    let buf = match MemoryMap::new(size, &[MapReadable, MapWritable,
                                   MapNonStandardFlags(STACK_FLAGS)]) {
      Ok(map) => map,
      Err(e) => panic!("mmap for stack of size {} failed: {}", size, e)
    };

    if !protect_last_page(&buf) {
      panic!("Could not memory-protect guard page. stack={}, errno={}",
             buf.data(), errno());
    }

    let valgrind_id = unsafe {
      platform::stack_register(buf.data().offset(buf.len() as int) as *const _,
                               buf.data() as *const _)
    };

    let stk = Stack::Managed {
      buf: buf,
      valgrind_id: valgrind_id
    };

    stk
  }

  pub unsafe fn native(limit: *const u8) -> Stack {
    Stack::Native {
      sp_limit: limit
    }
  }

  pub fn top(&self) -> *mut u8 {
    unsafe {
      match *self {
        Stack::Native { .. } => ptr::null_mut(),
        Stack::Managed { ref buf, .. } => {
          buf.data().offset(buf.len() as int)
        }
      }
    }
  }

  pub fn limit(&self) -> *const u8 {
    unsafe {
      match *self {
        Stack::Native { sp_limit, .. } => sp_limit,
        Stack::Managed { ref buf, .. } => {
          buf.data().offset(page_size() as int) as *const _
        }
      }
    }
  }
}

fn protect_last_page(stack: &MemoryMap) -> bool {
  unsafe {
    let last_page = stack.data() as *mut libc::c_void;
    libc::mprotect(last_page, page_size() as libc::size_t,
                   libc::PROT_NONE) != -1
  }
}

impl Drop for Stack {
  fn drop(&mut self) {
    match *self {
      Stack::Native { .. } => {},
      Stack::Managed { valgrind_id, .. } => unsafe {
        platform::stack_deregister(valgrind_id);
      }
    }
  }
}
<commit_msg>Stack.top returns a mutable pointer, so it should take &mut self<commit_after>use libc;
use platform;
use std::ptr;
use std::os::{errno, page_size, MemoryMap, MapReadable, MapWritable,
              MapNonStandardFlags};

const STACK_FLAGS: libc::c_int = libc::MAP_STACK
                               | libc::MAP_PRIVATE
                               | libc::MAP_ANON;

pub enum Stack {
  Native {
    sp_limit: *const u8
  },
  Managed {
    buf: MemoryMap,
    valgrind_id: libc::c_uint
  }
}

impl Stack {
  pub fn new(size: uint) -> Stack {
    let buf = match MemoryMap::new(size, &[MapReadable, MapWritable,
                                   MapNonStandardFlags(STACK_FLAGS)]) {
      Ok(map) => map,
      Err(e) => panic!("mmap for stack of size {} failed: {}", size, e)
    };

    if !protect_last_page(&buf) {
      panic!("Could not memory-protect guard page. stack={}, errno={}",
             buf.data(), errno());
    }

    let valgrind_id = unsafe {
      platform::stack_register(buf.data().offset(buf.len() as int) as *const _,
                               buf.data() as *const _)
    };

    let stk = Stack::Managed {
      buf: buf,
      valgrind_id: valgrind_id
    };

    stk
  }

  pub unsafe fn native(limit: *const u8) -> Stack {
    Stack::Native {
      sp_limit: limit
    }
  }

  pub fn top(&mut self) -> *mut u8 {
    unsafe {
      match *self {
        Stack::Native { .. } => ptr::null_mut(),
        Stack::Managed { ref buf, .. } => {
          buf.data().offset(buf.len() as int)
        }
      }
    }
  }

  pub fn limit(&self) -> *const u8 {
    unsafe {
      match *self {
        Stack::Native { sp_limit, .. } => sp_limit,
        Stack::Managed { ref buf, .. } => {
          buf.data().offset(page_size() as int) as *const _
        }
      }
    }
  }
}

fn protect_last_page(stack: &MemoryMap) -> bool {
  unsafe {
    let last_page = stack.data() as *mut libc::c_void;
    libc::mprotect(last_page, page_size() as libc::size_t,
                   libc::PROT_NONE) != -1
  }
}

impl Drop for Stack {
  fn drop(&mut self) {
    match *self {
      Stack::Native { .. } => {},
      Stack::Managed { valgrind_id, .. } => unsafe {
        platform::stack_deregister(valgrind_id);
      }
    }
  }
}
<|endoftext|>


<commit_before><commit_msg>Refactor tests a little<commit_after><|endoftext|>


<commit_before><commit_msg>Initial dumb TCP server.<commit_after>use std::io::{TcpListener, TcpStream, BufferedReader};
use std::io::{Acceptor, Listener};

fn main() {
    println!("hello?");

    let socket = TcpListener::bind("127.0.0.1", 8080);

    let mut acceptor = socket.listen();

    for stream in acceptor.incoming() {
        match stream {
            Err(e) => {}
            Ok(stream) => spawn(proc() {
                println!("New client!");
                let mut socket = BufferedReader::new(stream);
                let content = socket.read_to_str();
                println!("{}", content.unwrap());
                println!("Gone!")
            })
        }
    }

    drop(acceptor)
}
<|endoftext|>


<commit_before><commit_msg>Fix typo in request line test<commit_after><|endoftext|>


<commit_before>#![feature(asm)]
#![feature(box_syntax)]
#![feature(core)]
#![feature(lang_items)]
#![feature(no_std)]
#![no_std]

extern crate core;

use core::mem::size_of;

use common::memory::*;
use common::string::*;

use drivers::keyboard::*;
use drivers::mouse::*;

use graphics::color::*;
use graphics::point::*;
use graphics::size::*;
use graphics::window::*;

use programs::session::*;

#[path="../src/common"]
mod common {
    pub mod debug;
    pub mod memory;
    pub mod pio;
    pub mod string;
    pub mod vector;
}

#[path="../src/drivers"]
mod drivers {
    pub mod disk;
    pub mod keyboard;
    pub mod mouse;
}

#[path="../src/filesystems"]
mod filesystems {
    pub mod unfs;
}

#[path="../src/graphics"]
mod graphics {
    pub mod bmp;
    pub mod color;
    pub mod display;
    pub mod point;
    pub mod size;
    pub mod window;
}

#[path="../src/programs"]
mod programs {
    pub mod session;
}

pub struct Application {
    window: Window,
    output: String,
    command: String,
    scroll: Point
}

impl Application {
    pub fn new() -> Application {
        Application {
            window: Window{
                point: Point::new(220, 100),
                size: Size::new(576, 400),
                title: String::from_str("Terminal"),
                title_color: Color::new(0, 0, 0),
                border_color: Color::new(196, 196, 255),
                content_color: Color::alpha(160, 160, 196, 196),
                shaded: false,
                closed: false,
                dragging: false,
                last_mouse_point: Point::new(0, 0),
                last_mouse_event: MouseEvent {
                    x: 0,
                    y: 0,
                    left_button: false,
                    right_button: false,
                    middle_button: false,
                    valid: false
                }
            },
            output: String::new(),
            command: String::new(),
            scroll: Point::new(0, 0)
        }
    }

    fn is_cmd(&self, name: &String) -> bool{
        return self.command.equals(name) || self.command.starts_with(&(name.clone() + " "));
    }

    fn append(&mut self, line: &String) {
        self.output = self.output.clone() + line + '\n';
    }

    #[allow(unused_variables)]
    unsafe fn on_command(&mut self, session: &mut Session){
        if self.is_cmd(&String::from_str("test")){
            self.append(&String::from_str("Test Command"));
        }else if self.is_cmd(&String::from_str("help")){
            self.append(&String::from_str("Help Command"));
        }
    }
}

impl SessionItem for Application {
    unsafe fn draw(&mut self, session: &mut Session) -> bool{
        let display = &session.display;
        if self.window.draw(display) {
            let scroll = self.scroll;

            let mut col = -scroll.x;
            let cols = self.window.size.width as isize / 8;
            let mut row = -scroll.y;
            let rows = self.window.size.height as isize / 16;

            for c in self.output.iter(){
                if c == '\n' {
                    col = -scroll.x;
                    row += 1;
                }else if c == '\t' {
                    col += 8 - col % 8;
                }else{
                    if col >= 0 && col < cols && row >= 0 && row < rows{
                        let point = Point::new(self.window.point.x + 8 * col, self.window.point.y + 16 * row);
                        display.char(point, c, Color::new(224, 224, 224));
                    }
                    col += 1;
                }
            }

            if col > -scroll.x {
                col = -scroll.x;
                row += 1;
            }

            if col >= 0 && col < cols && row >= 0 && row < rows{
                let point = Point::new(self.window.point.x + 8 * col, self.window.point.y + 16 * row);
                display.char(point, '#', Color::new(255, 255, 255));
                col += 2;
            }

            for c in self.command.iter(){
                if c == '\n' {
                    col = -scroll.x;
                    row += 1;
                }else if c == '\t' {
                    col += 8 - col % 8;
                }else{
                    if col >= 0 && col < cols && row >= 0 && row < rows{
                        let point = Point::new(self.window.point.x + 8 * col, self.window.point.y + 16 * row);
                        display.char(point, c, Color::new(255, 255, 255));
                    }
                    col += 1;
                }
            }

            if row >= rows {
                self.scroll.y += row - rows + 1;
                session.redraw = true;
            }

            if col >= 0 && col < cols && row >= 0 && row < rows{
                let point = Point::new(self.window.point.x + 8 * col, self.window.point.y + 16 * row);
                display.char(point, '_', Color::new(255, 255, 255));
            }

            return true;
        }else{
            return false;
        }
    }

    #[allow(unused_variables)]
    unsafe fn on_key(&mut self, session: &mut Session, key_event: KeyEvent){
        if key_event.pressed {
            match key_event.scancode {
                0x01 => self.window.closed = true,
                _ => ()
            }

            match key_event.character {
                '\x00' => (),
                '\x08' => {
                    if self.command.len() > 0 {
                        self.command = self.command.substr(0, self.command.len() - 1);
                    }
                }
                '\x1B' => self.command = String::new(),
                '\n' => {
                    if self.command.len() > 0 {
                        self.output = self.output.clone() + (self.command.clone() + '\n');
                        self.on_command(session);
                        self.command = String::new();
                    }
                },
                _ => {
                    self.command = self.command.clone() + key_event.character;
                }
            }
        }
    }

    unsafe fn on_mouse(&mut self, session: &mut Session, mouse_event: MouseEvent, allow_catch: bool) -> bool{
        return self.window.on_mouse(session.mouse_point, mouse_event, allow_catch);
    }
}

//Class wrappers

static mut application: *mut Application = 0 as *mut Application;

#[no_mangle]
pub unsafe fn entry(){
    application = alloc(size_of::<Application>()) as *mut Application;
    *application = Application::new();
}

#[no_mangle]
pub unsafe fn draw(session: &mut Session) -> bool{
    if application as usize > 0 {
        return (*application).draw(session);
    }else{
        return false;
    }
}

#[no_mangle]
pub unsafe fn on_key(session: &mut Session, key_event: KeyEvent){
    if application as usize > 0{
        (*application).on_key(session, key_event);
    }
}

#[no_mangle]
pub unsafe fn on_mouse(session: &mut Session, mouse_event: MouseEvent, allow_catch: bool) -> bool{
    if application as usize > 0 {
        return (*application).on_mouse(session, mouse_event, allow_catch);
    }else{
        return false;
    }
}
<commit_msg>Line editing in terminal example<commit_after>#![feature(asm)]
#![feature(box_syntax)]
#![feature(core)]
#![feature(lang_items)]
#![feature(no_std)]
#![no_std]

extern crate core;

use core::mem::size_of;

use common::debug::*;
use common::memory::*;
use common::string::*;

use drivers::keyboard::*;
use drivers::mouse::*;

use graphics::color::*;
use graphics::point::*;
use graphics::size::*;
use graphics::window::*;

use programs::session::*;

#[path="../src/common"]
mod common {
    pub mod debug;
    pub mod memory;
    pub mod pio;
    pub mod string;
    pub mod vector;
}

#[path="../src/drivers"]
mod drivers {
    pub mod disk;
    pub mod keyboard;
    pub mod mouse;
}

#[path="../src/filesystems"]
mod filesystems {
    pub mod unfs;
}

#[path="../src/graphics"]
mod graphics {
    pub mod bmp;
    pub mod color;
    pub mod display;
    pub mod point;
    pub mod size;
    pub mod window;
}

#[path="../src/programs"]
mod programs {
    pub mod session;
}

pub struct Application {
    window: Window,
    output: String,
    command: String,
    offset: usize,
    scroll: Point,
    wrap: bool
}

impl Application {
    pub fn new() -> Application {
        Application {
            window: Window{
                point: Point::new(220, 100),
                size: Size::new(576, 400),
                title: String::from_str("Terminal"),
                title_color: Color::new(0, 0, 0),
                border_color: Color::new(196, 196, 255),
                content_color: Color::alpha(160, 160, 196, 196),
                shaded: false,
                closed: false,
                dragging: false,
                last_mouse_point: Point::new(0, 0),
                last_mouse_event: MouseEvent {
                    x: 0,
                    y: 0,
                    left_button: false,
                    right_button: false,
                    middle_button: false,
                    valid: false
                }
            },
            output: String::new(),
            command: String::new(),
            offset: 0,
            scroll: Point::new(0, 0),
            wrap: true
        }
    }

    fn is_cmd(&self, name: &String) -> bool{
        return self.command.equals(name) || self.command.starts_with(&(name.clone() + " "));
    }

    fn append(&mut self, line: &String) {
        self.output = self.output.clone() + line + '\n';
    }

    #[allow(unused_variables)]
    unsafe fn on_command(&mut self, session: &mut Session){
        if self.is_cmd(&String::from_str("test")){
            self.append(&String::from_str("Test Command"));
        }else if self.is_cmd(&String::from_str("help")){
            self.append(&String::from_str("Help Command"));
        }
    }
}

impl SessionItem for Application {
    unsafe fn draw(&mut self, session: &mut Session) -> bool{
        let display = &session.display;
        if self.window.draw(display) {
            let scroll = self.scroll;

            let mut col = -scroll.x;
            let cols = self.window.size.width as isize / 8;
            let mut row = -scroll.y;
            let rows = self.window.size.height as isize / 16;

            for c in self.output.iter(){
                if self.wrap && col >= cols {
                    col = -scroll.x;
                    row += 1;
                }

                if c == '\n' {
                    col = -scroll.x;
                    row += 1;
                }else if c == '\t' {
                    col += 8 - col % 8;
                }else{
                    if col >= 0 && col < cols && row >= 0 && row < rows{
                        let point = Point::new(self.window.point.x + 8 * col, self.window.point.y + 16 * row);
                        display.char(point, c, Color::new(224, 224, 224));
                    }
                    col += 1;
                }
            }

            if col > -scroll.x {
                col = -scroll.x;
                row += 1;
            }

            if col >= 0 && col < cols && row >= 0 && row < rows{
                let point = Point::new(self.window.point.x + 8 * col, self.window.point.y + 16 * row);
                display.char(point, '#', Color::new(255, 255, 255));
                col += 2;
            }

            let mut i = 0;
            for c in self.command.iter(){
                if self.wrap && col >= cols {
                    col = -scroll.x;
                    row += 1;
                }

                if self.offset == i && col >= 0 && col < cols && row >= 0 && row < rows{
                    let point = Point::new(self.window.point.x + 8 * col, self.window.point.y + 16 * row);
                    display.char(point, '_', Color::new(255, 255, 255));
                }

                if c == '\n' {
                    col = -scroll.x;
                    row += 1;
                }else if c == '\t' {
                    col += 8 - col % 8;
                }else{
                    if col >= 0 && col < cols && row >= 0 && row < rows{
                        let point = Point::new(self.window.point.x + 8 * col, self.window.point.y + 16 * row);
                        display.char(point, c, Color::new(255, 255, 255));
                    }
                    col += 1;
                }

                i += 1;
            }

            if self.wrap && col >= cols {
                col = -scroll.x;
                row += 1;
            }

            if row >= rows {
                self.scroll.y += row - rows + 1;
                session.redraw = true;
            }

            if self.offset == i && col >= 0 && col < cols && row >= 0 && row < rows{
                let point = Point::new(self.window.point.x + 8 * col, self.window.point.y + 16 * row);
                display.char(point, '_', Color::new(255, 255, 255));
            }

            return true;
        }else{
            return false;
        }
    }

    #[allow(unused_variables)]
    unsafe fn on_key(&mut self, session: &mut Session, key_event: KeyEvent){
        if key_event.pressed {
            match key_event.scancode {
                0x01 => self.window.closed = true,
                0x47 => self.offset = 0,
                0x4B => if self.offset > 0 {
                    self.offset -= 1;
                },
                0x4D => if self.offset < self.command.len() {
                    self.offset += 1;
                },
                0x4F => self.offset = self.command.len(),
                _ => ()
            }

            match key_event.character {
                '\x00' => (),
                '\x08' => {
                    if self.offset > 0 {
                        self.command = self.command.substr(0, self.offset - 1) + self.command.substr(self.offset, self.command.len() - self.offset);
                        self.offset -= 1;
                    }
                }
                '\x1B' => self.command = String::new(),
                '\n' => {
                    if self.command.len() > 0 {
                        self.output = self.output.clone() + (self.command.clone() + '\n');
                        self.on_command(session);
                        self.command = String::new();
                        self.offset = 0;
                    }
                },
                _ => {
                    self.command = self.command.substr(0, self.offset) + key_event.character + self.command.substr(self.offset, self.command.len() - self.offset);
                    self.offset += 1;
                }
            }
        }
    }

    unsafe fn on_mouse(&mut self, session: &mut Session, mouse_event: MouseEvent, allow_catch: bool) -> bool{
        return self.window.on_mouse(session.mouse_point, mouse_event, allow_catch);
    }
}

//Class wrappers

static mut application: *mut Application = 0 as *mut Application;

#[no_mangle]
pub unsafe fn entry(){
    application = alloc(size_of::<Application>()) as *mut Application;
    *application = Application::new();
}

#[no_mangle]
pub unsafe fn draw(session: &mut Session) -> bool{
    if application as usize > 0 {
        return (*application).draw(session);
    }else{
        return false;
    }
}

#[no_mangle]
pub unsafe fn on_key(session: &mut Session, key_event: KeyEvent){
    if application as usize > 0{
        (*application).on_key(session, key_event);
    }
}

#[no_mangle]
pub unsafe fn on_mouse(session: &mut Session, mouse_event: MouseEvent, allow_catch: bool) -> bool{
    if application as usize > 0 {
        return (*application).on_mouse(session, mouse_event, allow_catch);
    }else{
        return false;
    }
}
<|endoftext|>


<commit_before><commit_msg>Don't panic on read byte from wait control reg<commit_after><|endoftext|>


<commit_before><commit_msg>Add compile-fail test for E0513<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.

use std::mem;

fn main() {
    unsafe {
        let size = mem::size_of::<u32>();
        mem::transmute_copy::<u32, [u8; size]>(&8_8); //~ ERROR E0513
                                                      //~| NOTE no type for variable
    }
}
<|endoftext|>


<commit_before><commit_msg>fetch/artifact: implement sha256 hash checking<commit_after><|endoftext|>