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

use net_traits::{ResourceAttribute, ResourceFetchTiming, ResourceTimeValue, ResourceTimingType};

#[test]
fn test_set_start_time_to_fetch_start_if_nonzero_tao() {
    let mut resource_timing: ResourceFetchTiming =
        ResourceFetchTiming::new(ResourceTimingType::Resource);
    resource_timing.fetch_start = 1;
    assert_eq!(resource_timing.start_time, 0, "`start_time` should be zero");
    assert!(
        resource_timing.fetch_start > 0,
        "`fetch_start` should have a positive value"
    );

    // verify that setting `start_time` to `fetch_start` succeeds
    resource_timing.set_attribute(ResourceAttribute::StartTime(ResourceTimeValue::FetchStart));
    assert_eq!(
        resource_timing.start_time, resource_timing.fetch_start,
        "`start_time` should equal `fetch_start`"
    );
}

#[test]
fn test_set_start_time_to_fetch_start_if_zero_tao() {
    let mut resource_timing: ResourceFetchTiming =
        ResourceFetchTiming::new(ResourceTimingType::Resource);
    resource_timing.start_time = 1;
    assert!(
        resource_timing.start_time > 0,
        "`start_time` should have a positive value"
    );
    assert_eq!(
        resource_timing.fetch_start, 0,
        "`fetch_start` should be zero"
    );

    // verify that setting `start_time` to `fetch_start` succeeds even when `fetch_start` == zero
    resource_timing.set_attribute(ResourceAttribute::StartTime(ResourceTimeValue::FetchStart));
    assert_eq!(
        resource_timing.start_time, resource_timing.fetch_start,
        "`start_time` should equal `fetch_start`"
    );
}

#[test]
fn test_set_start_time_to_fetch_start_if_nonzero_no_tao() {
    let mut resource_timing: ResourceFetchTiming =
        ResourceFetchTiming::new(ResourceTimingType::Resource);
    resource_timing.mark_timing_check_failed();
    resource_timing.fetch_start = 1;
    assert_eq!(resource_timing.start_time, 0, "`start_time` should be zero");
    assert!(
        resource_timing.fetch_start > 0,
        "`fetch_start` should have a positive value"
    );

    // verify that setting `start_time` to `fetch_start` succeeds even when TAO check failed
    resource_timing.set_attribute(ResourceAttribute::StartTime(ResourceTimeValue::FetchStart));
    assert_eq!(
        resource_timing.start_time, resource_timing.fetch_start,
        "`start_time` should equal `fetch_start`"
    );
}

#[test]
fn test_set_start_time_to_fetch_start_if_zero_no_tao() {
    let mut resource_timing: ResourceFetchTiming =
        ResourceFetchTiming::new(ResourceTimingType::Resource);
    resource_timing.mark_timing_check_failed();
    resource_timing.start_time = 1;
    assert!(
        resource_timing.start_time > 0,
        "`start_time` should have a positive value"
    );
    assert_eq!(
        resource_timing.fetch_start, 0,
        "`fetch_start` should be zero"
    );

    // verify that setting `start_time` to `fetch_start` succeeds even when `fetch_start`==0 and no TAO
    resource_timing.set_attribute(ResourceAttribute::StartTime(ResourceTimeValue::FetchStart));
    assert_eq!(
        resource_timing.start_time, resource_timing.fetch_start,
        "`start_time` should equal `fetch_start`"
    );
}

#[test]
fn test_set_start_time_to_redirect_start_if_nonzero_tao() {
    let mut resource_timing: ResourceFetchTiming =
        ResourceFetchTiming::new(ResourceTimingType::Resource);
    resource_timing.redirect_start = 1;
    assert_eq!(resource_timing.start_time, 0, "`start_time` should be zero");
    assert!(
        resource_timing.redirect_start > 0,
        "`redirect_start` should have a positive value"
    );

    // verify that setting `start_time` to `redirect_start` succeeds for nonzero `redirect_start`, TAO pass
    resource_timing.set_attribute(ResourceAttribute::StartTime(
        ResourceTimeValue::RedirectStart,
    ));
    assert_eq!(
        resource_timing.start_time, resource_timing.redirect_start,
        "`start_time` should equal `redirect_start`"
    );
}

#[test]
fn test_not_set_start_time_to_redirect_start_if_zero_tao() {
    let mut resource_timing: ResourceFetchTiming =
        ResourceFetchTiming::new(ResourceTimingType::Resource);
    resource_timing.start_time = 1;
    assert!(
        resource_timing.start_time > 0,
        "`start_time` should have a positive value"
    );
    assert_eq!(
        resource_timing.redirect_start, 0,
        "`redirect_start` should be zero"
    );

    // verify that setting `start_time` to `redirect_start` fails if `redirect_start` == 0
    resource_timing.set_attribute(ResourceAttribute::StartTime(
        ResourceTimeValue::RedirectStart,
    ));
    assert_ne!(
        resource_timing.start_time, resource_timing.redirect_start,
        "`start_time` should *not* equal `redirect_start`"
    );
}

#[test]
fn test_not_set_start_time_to_redirect_start_if_nonzero_no_tao() {
    let mut resource_timing: ResourceFetchTiming =
        ResourceFetchTiming::new(ResourceTimingType::Resource);
    resource_timing.mark_timing_check_failed();
    // Note: properly-behaved redirect_start should never be nonzero once TAO check has failed
    resource_timing.redirect_start = 1;
    assert_eq!(resource_timing.start_time, 0, "`start_time` should be zero");
    assert!(
        resource_timing.redirect_start > 0,
        "`redirect_start` should have a positive value"
    );

    // verify that setting `start_time` to `redirect_start` fails if TAO check fails
    resource_timing.set_attribute(ResourceAttribute::StartTime(
        ResourceTimeValue::RedirectStart,
    ));
    assert_ne!(
        resource_timing.start_time, resource_timing.redirect_start,
        "`start_time` should *not* equal `redirect_start`"
    );
}

#[test]
fn test_not_set_start_time_to_redirect_start_if_zero_no_tao() {
    let mut resource_timing: ResourceFetchTiming =
        ResourceFetchTiming::new(ResourceTimingType::Resource);
    resource_timing.mark_timing_check_failed();
    resource_timing.start_time = 1;
    assert!(
        resource_timing.start_time > 0,
        "`start_time` should have a positive value"
    );
    assert_eq!(
        resource_timing.redirect_start, 0,
        "`redirect_start` should be zero"
    );

    // verify that setting `start_time` to `redirect_start` fails if `redirect_start`==0 and no TAO
    resource_timing.set_attribute(ResourceAttribute::StartTime(
        ResourceTimeValue::RedirectStart,
    ));
    assert_ne!(
        resource_timing.start_time, resource_timing.redirect_start,
        "`start_time` should *not* equal `redirect_start`"
    );
}

#[test]
fn test_set_start_time() {
    let mut resource_timing: ResourceFetchTiming =
        ResourceFetchTiming::new(ResourceTimingType::Resource);
    assert_eq!(
        resource_timing.start_time, 0,
        "initial `start_time` should be zero"
    );

    // verify setting `start_time` to current time succeeds
    resource_timing.set_attribute(ResourceAttribute::StartTime(ResourceTimeValue::Now));
    assert!(resource_timing.start_time > 0, "failed to set `start_time`");
}
#[test]
fn test_reset_start_time() {
    let mut resource_timing: ResourceFetchTiming =
        ResourceFetchTiming::new(ResourceTimingType::Resource);
    assert_eq!(resource_timing.start_time, 0, "initial `start_time` = 0");

    resource_timing.start_time = 1;
    assert!(
        resource_timing.start_time > 0,
        "`start_time` should have a positive value"
    );

    // verify resetting `start_time` (to zero) succeeds
    resource_timing.set_attribute(ResourceAttribute::StartTime(ResourceTimeValue::Zero));
    assert_eq!(
        resource_timing.start_time, 0,
        "failed to reset `start_time`"
    );
}
<commit_msg>Minor assert message edits for consistency<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */

use net_traits::{ResourceAttribute, ResourceFetchTiming, ResourceTimeValue, ResourceTimingType};

#[test]
fn test_set_start_time_to_fetch_start_if_nonzero_tao() {
    let mut resource_timing: ResourceFetchTiming =
        ResourceFetchTiming::new(ResourceTimingType::Resource);
    resource_timing.fetch_start = 1;
    assert_eq!(resource_timing.start_time, 0, "`start_time` should be zero");
    assert!(
        resource_timing.fetch_start > 0,
        "`fetch_start` should have a positive value"
    );

    // verify that setting `start_time` to `fetch_start` succeeds
    resource_timing.set_attribute(ResourceAttribute::StartTime(ResourceTimeValue::FetchStart));
    assert_eq!(
        resource_timing.start_time, resource_timing.fetch_start,
        "`start_time` should equal `fetch_start`"
    );
}

#[test]
fn test_set_start_time_to_fetch_start_if_zero_tao() {
    let mut resource_timing: ResourceFetchTiming =
        ResourceFetchTiming::new(ResourceTimingType::Resource);
    resource_timing.start_time = 1;
    assert!(
        resource_timing.start_time > 0,
        "`start_time` should have a positive value"
    );
    assert_eq!(
        resource_timing.fetch_start, 0,
        "`fetch_start` should be zero"
    );

    // verify that setting `start_time` to `fetch_start` succeeds even when `fetch_start` == zero
    resource_timing.set_attribute(ResourceAttribute::StartTime(ResourceTimeValue::FetchStart));
    assert_eq!(
        resource_timing.start_time, resource_timing.fetch_start,
        "`start_time` should equal `fetch_start`"
    );
}

#[test]
fn test_set_start_time_to_fetch_start_if_nonzero_no_tao() {
    let mut resource_timing: ResourceFetchTiming =
        ResourceFetchTiming::new(ResourceTimingType::Resource);
    resource_timing.mark_timing_check_failed();
    resource_timing.fetch_start = 1;
    assert_eq!(resource_timing.start_time, 0, "`start_time` should be zero");
    assert!(
        resource_timing.fetch_start > 0,
        "`fetch_start` should have a positive value"
    );

    // verify that setting `start_time` to `fetch_start` succeeds even when TAO check failed
    resource_timing.set_attribute(ResourceAttribute::StartTime(ResourceTimeValue::FetchStart));
    assert_eq!(
        resource_timing.start_time, resource_timing.fetch_start,
        "`start_time` should equal `fetch_start`"
    );
}

#[test]
fn test_set_start_time_to_fetch_start_if_zero_no_tao() {
    let mut resource_timing: ResourceFetchTiming =
        ResourceFetchTiming::new(ResourceTimingType::Resource);
    resource_timing.mark_timing_check_failed();
    resource_timing.start_time = 1;
    assert!(
        resource_timing.start_time > 0,
        "`start_time` should have a positive value"
    );
    assert_eq!(
        resource_timing.fetch_start, 0,
        "`fetch_start` should be zero"
    );

    // verify that setting `start_time` to `fetch_start` succeeds even when `fetch_start`==0 and no TAO
    resource_timing.set_attribute(ResourceAttribute::StartTime(ResourceTimeValue::FetchStart));
    assert_eq!(
        resource_timing.start_time, resource_timing.fetch_start,
        "`start_time` should equal `fetch_start`"
    );
}

#[test]
fn test_set_start_time_to_redirect_start_if_nonzero_tao() {
    let mut resource_timing: ResourceFetchTiming =
        ResourceFetchTiming::new(ResourceTimingType::Resource);
    resource_timing.redirect_start = 1;
    assert_eq!(resource_timing.start_time, 0, "`start_time` should be zero");
    assert!(
        resource_timing.redirect_start > 0,
        "`redirect_start` should have a positive value"
    );

    // verify that setting `start_time` to `redirect_start` succeeds for nonzero `redirect_start`, TAO pass
    resource_timing.set_attribute(ResourceAttribute::StartTime(
        ResourceTimeValue::RedirectStart,
    ));
    assert_eq!(
        resource_timing.start_time, resource_timing.redirect_start,
        "`start_time` should equal `redirect_start`"
    );
}

#[test]
fn test_not_set_start_time_to_redirect_start_if_zero_tao() {
    let mut resource_timing: ResourceFetchTiming =
        ResourceFetchTiming::new(ResourceTimingType::Resource);
    resource_timing.start_time = 1;
    assert!(
        resource_timing.start_time > 0,
        "`start_time` should have a positive value"
    );
    assert_eq!(
        resource_timing.redirect_start, 0,
        "`redirect_start` should be zero"
    );

    // verify that setting `start_time` to `redirect_start` fails if `redirect_start` == 0
    resource_timing.set_attribute(ResourceAttribute::StartTime(
        ResourceTimeValue::RedirectStart,
    ));
    assert_ne!(
        resource_timing.start_time, resource_timing.redirect_start,
        "`start_time` should *not* equal `redirect_start`"
    );
}

#[test]
fn test_not_set_start_time_to_redirect_start_if_nonzero_no_tao() {
    let mut resource_timing: ResourceFetchTiming =
        ResourceFetchTiming::new(ResourceTimingType::Resource);
    resource_timing.mark_timing_check_failed();
    // Note: properly-behaved redirect_start should never be nonzero once TAO check has failed
    resource_timing.redirect_start = 1;
    assert_eq!(resource_timing.start_time, 0, "`start_time` should be zero");
    assert!(
        resource_timing.redirect_start > 0,
        "`redirect_start` should have a positive value"
    );

    // verify that setting `start_time` to `redirect_start` fails if TAO check fails
    resource_timing.set_attribute(ResourceAttribute::StartTime(
        ResourceTimeValue::RedirectStart,
    ));
    assert_ne!(
        resource_timing.start_time, resource_timing.redirect_start,
        "`start_time` should *not* equal `redirect_start`"
    );
}

#[test]
fn test_not_set_start_time_to_redirect_start_if_zero_no_tao() {
    let mut resource_timing: ResourceFetchTiming =
        ResourceFetchTiming::new(ResourceTimingType::Resource);
    resource_timing.mark_timing_check_failed();
    resource_timing.start_time = 1;
    assert!(
        resource_timing.start_time > 0,
        "`start_time` should have a positive value"
    );
    assert_eq!(
        resource_timing.redirect_start, 0,
        "`redirect_start` should be zero"
    );

    // verify that setting `start_time` to `redirect_start` fails if `redirect_start`==0 and no TAO
    resource_timing.set_attribute(ResourceAttribute::StartTime(
        ResourceTimeValue::RedirectStart,
    ));
    assert_ne!(
        resource_timing.start_time, resource_timing.redirect_start,
        "`start_time` should *not* equal `redirect_start`"
    );
}

#[test]
fn test_set_start_time() {
    let mut resource_timing: ResourceFetchTiming =
        ResourceFetchTiming::new(ResourceTimingType::Resource);
    assert_eq!(resource_timing.start_time, 0, "`start_time` should be zero");

    // verify setting `start_time` to current time succeeds
    resource_timing.set_attribute(ResourceAttribute::StartTime(ResourceTimeValue::Now));
    assert!(resource_timing.start_time > 0, "failed to set `start_time`");
}
#[test]
fn test_reset_start_time() {
    let mut resource_timing: ResourceFetchTiming =
        ResourceFetchTiming::new(ResourceTimingType::Resource);
    assert_eq!(resource_timing.start_time, 0, "`start_time` should be zero");

    resource_timing.start_time = 1;
    assert!(
        resource_timing.start_time > 0,
        "`start_time` should have a positive value"
    );

    // verify resetting `start_time` (to zero) succeeds
    resource_timing.set_attribute(ResourceAttribute::StartTime(ResourceTimeValue::Zero));
    assert_eq!(
        resource_timing.start_time, 0,
        "failed to reset `start_time`"
    );
}
<|endoftext|>


<commit_before><commit_msg>Fix else if branches<commit_after><|endoftext|>


<commit_before><commit_msg>Propogate PrefixFreeDecodeError<commit_after><|endoftext|>


<commit_before><commit_msg>Upgrade variables to 64 bit<commit_after><|endoftext|>


<commit_before><commit_msg>...somehow I was missing this file<commit_after>use capnp::list::{struct_list};
use holmes_capnp::holmes;

use std::str::FromStr;
use std::string::{ToString, String};

pub type PredId = u64;

#[derive(Copy,PartialEq,Clone)]
pub enum HType {
  UInt64,
  HString,
  Blob
}
use native_types::HType::*;

impl FromStr for HType {
  fn from_str(s : &str) -> Option<HType> {
    match s {
      "uint64" => {Some(UInt64)}
      "string" => {Some(HString)}
      "blob"   => {Some(Blob)}
      _ => {None}
    }
  }
}

impl ToString for HType {
  fn to_string(&self) -> String {
    String::from_str(match self {
      &UInt64  => {"uint64"}
      &HString => {"string"}
      &Blob    => {"blob"}
    })
  }
}

#[derive(PartialEq,Clone)]
pub struct Predicate {
  pub name  : String,
  pub types : Vec<HType>
}

pub fn convert_types<'a> (types_reader : struct_list::Reader<'a, holmes::h_type::Reader<'a>>)
   -> Vec<HType> {
  let mut types = Vec::new();
  for type_reader in types_reader.iter() {
    match type_reader.which() {
      Some(holmes::h_type::Uint64(())) => {types.push(UInt64);}
      Some(holmes::h_type::String(())) => {types.push(HString);}
      Some(holmes::h_type::Blob(())) => {types.push(Blob);}
      None => { } //TODO: What should we do if there's an unknown type?
    }
  }
  types
}
<|endoftext|>


<commit_before>use std::cmp;
use std::fmt::{self, Debug, Formatter};
use std::fs;
use std::io::prelude::*;
use std::path::{Path, PathBuf};

use filetime::FileTime;
use git2;
use glob::Pattern;

use core::{Package, PackageId, Summary, SourceId, Source, Dependency, Registry};
use ops;
use util::{self, CargoResult, internal, internal_error, human, ChainError};
use util::Config;

pub struct PathSource<'cfg> {
    id: SourceId,
    path: PathBuf,
    updated: bool,
    packages: Vec<Package>,
    config: &'cfg Config,
}

// TODO: Figure out if packages should be discovered in new or self should be
// mut and packages are discovered in update
impl<'cfg> PathSource<'cfg> {
    pub fn for_path(path: &Path, config: &'cfg Config)
                    -> CargoResult<PathSource<'cfg>> {
        trace!("PathSource::for_path; path={}", path.display());
        Ok(PathSource::new(path, &try!(SourceId::for_path(path)), config))
    }

    /// Invoked with an absolute path to a directory that contains a Cargo.toml.
    /// The source will read the manifest and find any other packages contained
    /// in the directory structure reachable by the root manifest.
    pub fn new(path: &Path, id: &SourceId, config: &'cfg Config)
               -> PathSource<'cfg> {
        trace!("new; id={}", id);

        PathSource {
            id: id.clone(),
            path: path.to_path_buf(),
            updated: false,
            packages: Vec::new(),
            config: config,
        }
    }

    pub fn root_package(&mut self) -> CargoResult<Package> {
        trace!("root_package; source={:?}", self);

        try!(self.update());

        match self.packages.iter().find(|p| p.root() == &*self.path) {
            Some(pkg) => Ok(pkg.clone()),
            None => Err(internal("no package found in source"))
        }
    }

    fn read_packages(&self) -> CargoResult<Vec<Package>> {
        if self.updated {
            Ok(self.packages.clone())
        } else if self.id.is_path() && self.id.precise().is_some() {
            // If our source id is a path and it's listed with a precise
            // version, then it means that we're not allowed to have nested
            // dependencies (they've been rewritten to crates.io dependencies)
            // In this case we specifically read just one package, not a list of
            // packages.
            let path = self.path.join("Cargo.toml");
            let (pkg, _) = try!(ops::read_package(&path, &self.id,
                                                  self.config));
            Ok(vec![pkg])
        } else {
            ops::read_packages(&self.path, &self.id, self.config)
        }
    }

    /// List all files relevant to building this package inside this source.
    ///
    /// This function will use the appropriate methods to determine the
    /// set of files underneath this source's directory which are relevant for
    /// building `pkg`.
    ///
    /// The basic assumption of this method is that all files in the directory
    /// are relevant for building this package, but it also contains logic to
    /// use other methods like .gitignore to filter the list of files.
    pub fn list_files(&self, pkg: &Package) -> CargoResult<Vec<PathBuf>> {
        let root = pkg.root();

        let parse = |p: &String| {
            Pattern::new(p).map_err(|e| {
                human(format!("could not parse pattern `{}`: {}", p, e))
            })
        };
        let exclude = try!(pkg.manifest().exclude().iter()
                              .map(|p| parse(p)).collect::<Result<Vec<_>, _>>());
        let include = try!(pkg.manifest().include().iter()
                              .map(|p| parse(p)).collect::<Result<Vec<_>, _>>());

        let mut filter = |p: &Path| {
            let relative_path = util::without_prefix(p, &root).unwrap();
            include.iter().any(|p| p.matches_path(&relative_path)) || {
                include.len() == 0 &&
                 !exclude.iter().any(|p| p.matches_path(&relative_path))
            }
        };

        // If this package is a git repository, then we really do want to query
        // the git repository as it takes into account items such as .gitignore.
        // We're not quite sure where the git repository is, however, so we do a
        // bit of a probe.
        //
        // We check all packages in this source that are ancestors of the
        // specified package (including the same package) to see if they're at
        // the root of the git repository. This isn't always true, but it'll get
        // us there most of the time!
        let repo = self.packages.iter()
                       .map(|pkg| pkg.root())
                       .filter(|path| root.starts_with(path))
                       .filter_map(|path| git2::Repository::open(&path).ok())
                       .next();
        match repo {
            Some(repo) => self.list_files_git(pkg, repo, &mut filter),
            None => self.list_files_walk(pkg, &mut filter),
        }
    }

    fn list_files_git(&self, pkg: &Package, repo: git2::Repository,
                      filter: &mut FnMut(&Path) -> bool)
                      -> CargoResult<Vec<PathBuf>> {
        warn!("list_files_git {}", pkg.package_id());
        let index = try!(repo.index());
        let root = try!(repo.workdir().chain_error(|| {
            internal_error("Can't list files on a bare repository.", "")
        }));
        let pkg_path = pkg.root();

        let mut ret = Vec::new();

        // We use information from the git repository to guide us in traversing
        // its tree. The primary purpose of this is to take advantage of the
        // .gitignore and auto-ignore files that don't matter.
        //
        // Here we're also careful to look at both tracked and untracked files as
        // the untracked files are often part of a build and may become relevant
        // as part of a future commit.
        let index_files = index.iter().map(|entry| {
            use libgit2_sys::git_filemode_t::GIT_FILEMODE_COMMIT;
            let is_dir = entry.mode == GIT_FILEMODE_COMMIT as u32;
            (join(&root, &entry.path), Some(is_dir))
        });
        let mut opts = git2::StatusOptions::new();
        opts.include_untracked(true);
        if let Some(suffix) = util::without_prefix(pkg_path, &root) {
            opts.pathspec(suffix);
        }
        let statuses = try!(repo.statuses(Some(&mut opts)));
        let untracked = statuses.iter().map(|entry| {
            (join(&root, entry.path_bytes()), None)
        });

        'outer: for (file_path, is_dir) in index_files.chain(untracked) {
            let file_path = try!(file_path);

            // Filter out files outside this package.
            if !file_path.starts_with(pkg_path) { continue }

            // Filter out Cargo.lock and target always
            {
                let fname = file_path.file_name().and_then(|s| s.to_str());
                if fname == Some("Cargo.lock") { continue }
                if fname == Some("target") { continue }
            }

            // Filter out sub-packages of this package
            for other_pkg in self.packages.iter().filter(|p| *p != pkg) {
                let other_path = other_pkg.root();
                if other_path.starts_with(pkg_path) &&
                   file_path.starts_with(other_path) {
                    continue 'outer;
                }
            }

            let is_dir = is_dir.or_else(|| {
                fs::metadata(&file_path).ok().map(|m| m.is_dir())
            }).unwrap_or(false);
            if is_dir {
                warn!("  found submodule {}", file_path.display());
                let rel = util::without_prefix(&file_path, &root).unwrap();
                let rel = try!(rel.to_str().chain_error(|| {
                    human(format!("invalid utf-8 filename: {}", rel.display()))
                }));
                // Git submodules are currently only named through `/` path
                // separators, explicitly not `\` which windows uses. Who knew?
                let rel = rel.replace(r"\", "/");
                match repo.find_submodule(&rel).and_then(|s| s.open()) {
                    Ok(repo) => {
                        let files = try!(self.list_files_git(pkg, repo, filter));
                        ret.extend(files.into_iter());
                    }
                    Err(..) => {
                        try!(PathSource::walk(&file_path, &mut ret, false,
                                              filter));
                    }
                }
            } else if (*filter)(&file_path) {
                // We found a file!
                warn!("  found {}", file_path.display());
                ret.push(file_path);
            }
        }
        return Ok(ret);

        #[cfg(unix)]
        fn join(path: &Path, data: &[u8]) -> CargoResult<PathBuf> {
            use std::os::unix::prelude::*;
            use std::ffi::OsStr;
            Ok(path.join(<OsStr as OsStrExt>::from_bytes(data)))
        }
        #[cfg(windows)]
        fn join(path: &Path, data: &[u8]) -> CargoResult<PathBuf> {
            use std::str;
            match str::from_utf8(data) {
                Ok(s) => Ok(path.join(s)),
                Err(..) => Err(internal("cannot process path in git with a non \
                                         unicode filename")),
            }
        }
    }

    fn list_files_walk(&self, pkg: &Package, filter: &mut FnMut(&Path) -> bool)
                       -> CargoResult<Vec<PathBuf>> {
        let mut ret = Vec::new();
        for pkg in self.packages.iter().filter(|p| *p == pkg) {
            let loc = pkg.root();
            try!(PathSource::walk(loc, &mut ret, true, filter));
        }
        return Ok(ret);
    }

    fn walk(path: &Path, ret: &mut Vec<PathBuf>,
            is_root: bool, filter: &mut FnMut(&Path) -> bool) -> CargoResult<()>
    {
        if !fs::metadata(&path).map(|m| m.is_dir()).unwrap_or(false) {
            if (*filter)(path) {
                ret.push(path.to_path_buf());
            }
            return Ok(())
        }
        // Don't recurse into any sub-packages that we have
        if !is_root && fs::metadata(&path.join("Cargo.toml")).is_ok() {
            return Ok(())
        }
        for dir in try!(fs::read_dir(path)) {
            let dir = try!(dir).path();
            let name = dir.file_name().and_then(|s| s.to_str());
            // Skip dotfile directories
            if name.map(|s| s.starts_with(".")) == Some(true) {
                continue
            } else if is_root {
                // Skip cargo artifacts
                match name {
                    Some("target") | Some("Cargo.lock") => continue,
                    _ => {}
                }
            }
            try!(PathSource::walk(&dir, ret, false, filter));
        }
        return Ok(())
    }
}

impl<'cfg> Debug for PathSource<'cfg> {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        write!(f, "the paths source")
    }
}

impl<'cfg> Registry for PathSource<'cfg> {
    fn query(&mut self, dep: &Dependency) -> CargoResult<Vec<Summary>> {
        self.packages.query(dep)
    }
}

impl<'cfg> Source for PathSource<'cfg> {
    fn update(&mut self) -> CargoResult<()> {
        if !self.updated {
            let packages = try!(self.read_packages());
            self.packages.extend(packages.into_iter());
            self.updated = true;
        }

        Ok(())
    }

    fn download(&mut self, _: &[PackageId])  -> CargoResult<()>{
        // TODO: assert! that the PackageId is contained by the source
        Ok(())
    }

    fn get(&self, ids: &[PackageId]) -> CargoResult<Vec<Package>> {
        trace!("getting packages; ids={:?}", ids);

        Ok(self.packages.iter()
           .filter(|pkg| ids.iter().any(|id| pkg.package_id() == id))
           .map(|pkg| pkg.clone())
           .collect())
    }

    fn fingerprint(&self, pkg: &Package) -> CargoResult<String> {
        if !self.updated {
            return Err(internal_error("BUG: source was not updated", ""));
        }

        let mut max = FileTime::zero();
        for file in try!(self.list_files(pkg)).iter() {
            // An fs::stat error here is either because path is a
            // broken symlink, a permissions error, or a race
            // condition where this path was rm'ed - either way,
            // we can ignore the error and treat the path's mtime
            // as 0.
            let mtime = fs::metadata(file).map(|meta| {
                FileTime::from_last_modification_time(&meta)
            }).unwrap_or(FileTime::zero());
            warn!("{} {}", mtime, file.display());
            max = cmp::max(max, mtime);
        }
        trace!("fingerprint {}: {}", self.path.display(), max);
        Ok(max.to_string())
    }
}
<commit_msg>Include filename in path fingerprint<commit_after>use std::fmt::{self, Debug, Formatter};
use std::fs;
use std::io::prelude::*;
use std::path::{Path, PathBuf};

use filetime::FileTime;
use git2;
use glob::Pattern;

use core::{Package, PackageId, Summary, SourceId, Source, Dependency, Registry};
use ops;
use util::{self, CargoResult, internal, internal_error, human, ChainError};
use util::Config;

pub struct PathSource<'cfg> {
    id: SourceId,
    path: PathBuf,
    updated: bool,
    packages: Vec<Package>,
    config: &'cfg Config,
}

// TODO: Figure out if packages should be discovered in new or self should be
// mut and packages are discovered in update
impl<'cfg> PathSource<'cfg> {
    pub fn for_path(path: &Path, config: &'cfg Config)
                    -> CargoResult<PathSource<'cfg>> {
        trace!("PathSource::for_path; path={}", path.display());
        Ok(PathSource::new(path, &try!(SourceId::for_path(path)), config))
    }

    /// Invoked with an absolute path to a directory that contains a Cargo.toml.
    /// The source will read the manifest and find any other packages contained
    /// in the directory structure reachable by the root manifest.
    pub fn new(path: &Path, id: &SourceId, config: &'cfg Config)
               -> PathSource<'cfg> {
        trace!("new; id={}", id);

        PathSource {
            id: id.clone(),
            path: path.to_path_buf(),
            updated: false,
            packages: Vec::new(),
            config: config,
        }
    }

    pub fn root_package(&mut self) -> CargoResult<Package> {
        trace!("root_package; source={:?}", self);

        try!(self.update());

        match self.packages.iter().find(|p| p.root() == &*self.path) {
            Some(pkg) => Ok(pkg.clone()),
            None => Err(internal("no package found in source"))
        }
    }

    fn read_packages(&self) -> CargoResult<Vec<Package>> {
        if self.updated {
            Ok(self.packages.clone())
        } else if self.id.is_path() && self.id.precise().is_some() {
            // If our source id is a path and it's listed with a precise
            // version, then it means that we're not allowed to have nested
            // dependencies (they've been rewritten to crates.io dependencies)
            // In this case we specifically read just one package, not a list of
            // packages.
            let path = self.path.join("Cargo.toml");
            let (pkg, _) = try!(ops::read_package(&path, &self.id,
                                                  self.config));
            Ok(vec![pkg])
        } else {
            ops::read_packages(&self.path, &self.id, self.config)
        }
    }

    /// List all files relevant to building this package inside this source.
    ///
    /// This function will use the appropriate methods to determine the
    /// set of files underneath this source's directory which are relevant for
    /// building `pkg`.
    ///
    /// The basic assumption of this method is that all files in the directory
    /// are relevant for building this package, but it also contains logic to
    /// use other methods like .gitignore to filter the list of files.
    pub fn list_files(&self, pkg: &Package) -> CargoResult<Vec<PathBuf>> {
        let root = pkg.root();

        let parse = |p: &String| {
            Pattern::new(p).map_err(|e| {
                human(format!("could not parse pattern `{}`: {}", p, e))
            })
        };
        let exclude = try!(pkg.manifest().exclude().iter()
                              .map(|p| parse(p)).collect::<Result<Vec<_>, _>>());
        let include = try!(pkg.manifest().include().iter()
                              .map(|p| parse(p)).collect::<Result<Vec<_>, _>>());

        let mut filter = |p: &Path| {
            let relative_path = util::without_prefix(p, &root).unwrap();
            include.iter().any(|p| p.matches_path(&relative_path)) || {
                include.len() == 0 &&
                 !exclude.iter().any(|p| p.matches_path(&relative_path))
            }
        };

        // If this package is a git repository, then we really do want to query
        // the git repository as it takes into account items such as .gitignore.
        // We're not quite sure where the git repository is, however, so we do a
        // bit of a probe.
        //
        // We check all packages in this source that are ancestors of the
        // specified package (including the same package) to see if they're at
        // the root of the git repository. This isn't always true, but it'll get
        // us there most of the time!
        let repo = self.packages.iter()
                       .map(|pkg| pkg.root())
                       .filter(|path| root.starts_with(path))
                       .filter_map(|path| git2::Repository::open(&path).ok())
                       .next();
        match repo {
            Some(repo) => self.list_files_git(pkg, repo, &mut filter),
            None => self.list_files_walk(pkg, &mut filter),
        }
    }

    fn list_files_git(&self, pkg: &Package, repo: git2::Repository,
                      filter: &mut FnMut(&Path) -> bool)
                      -> CargoResult<Vec<PathBuf>> {
        warn!("list_files_git {}", pkg.package_id());
        let index = try!(repo.index());
        let root = try!(repo.workdir().chain_error(|| {
            internal_error("Can't list files on a bare repository.", "")
        }));
        let pkg_path = pkg.root();

        let mut ret = Vec::new();

        // We use information from the git repository to guide us in traversing
        // its tree. The primary purpose of this is to take advantage of the
        // .gitignore and auto-ignore files that don't matter.
        //
        // Here we're also careful to look at both tracked and untracked files as
        // the untracked files are often part of a build and may become relevant
        // as part of a future commit.
        let index_files = index.iter().map(|entry| {
            use libgit2_sys::git_filemode_t::GIT_FILEMODE_COMMIT;
            let is_dir = entry.mode == GIT_FILEMODE_COMMIT as u32;
            (join(&root, &entry.path), Some(is_dir))
        });
        let mut opts = git2::StatusOptions::new();
        opts.include_untracked(true);
        if let Some(suffix) = util::without_prefix(pkg_path, &root) {
            opts.pathspec(suffix);
        }
        let statuses = try!(repo.statuses(Some(&mut opts)));
        let untracked = statuses.iter().map(|entry| {
            (join(&root, entry.path_bytes()), None)
        });

        'outer: for (file_path, is_dir) in index_files.chain(untracked) {
            let file_path = try!(file_path);

            // Filter out files outside this package.
            if !file_path.starts_with(pkg_path) { continue }

            // Filter out Cargo.lock and target always
            {
                let fname = file_path.file_name().and_then(|s| s.to_str());
                if fname == Some("Cargo.lock") { continue }
                if fname == Some("target") { continue }
            }

            // Filter out sub-packages of this package
            for other_pkg in self.packages.iter().filter(|p| *p != pkg) {
                let other_path = other_pkg.root();
                if other_path.starts_with(pkg_path) &&
                   file_path.starts_with(other_path) {
                    continue 'outer;
                }
            }

            let is_dir = is_dir.or_else(|| {
                fs::metadata(&file_path).ok().map(|m| m.is_dir())
            }).unwrap_or(false);
            if is_dir {
                warn!("  found submodule {}", file_path.display());
                let rel = util::without_prefix(&file_path, &root).unwrap();
                let rel = try!(rel.to_str().chain_error(|| {
                    human(format!("invalid utf-8 filename: {}", rel.display()))
                }));
                // Git submodules are currently only named through `/` path
                // separators, explicitly not `\` which windows uses. Who knew?
                let rel = rel.replace(r"\", "/");
                match repo.find_submodule(&rel).and_then(|s| s.open()) {
                    Ok(repo) => {
                        let files = try!(self.list_files_git(pkg, repo, filter));
                        ret.extend(files.into_iter());
                    }
                    Err(..) => {
                        try!(PathSource::walk(&file_path, &mut ret, false,
                                              filter));
                    }
                }
            } else if (*filter)(&file_path) {
                // We found a file!
                warn!("  found {}", file_path.display());
                ret.push(file_path);
            }
        }
        return Ok(ret);

        #[cfg(unix)]
        fn join(path: &Path, data: &[u8]) -> CargoResult<PathBuf> {
            use std::os::unix::prelude::*;
            use std::ffi::OsStr;
            Ok(path.join(<OsStr as OsStrExt>::from_bytes(data)))
        }
        #[cfg(windows)]
        fn join(path: &Path, data: &[u8]) -> CargoResult<PathBuf> {
            use std::str;
            match str::from_utf8(data) {
                Ok(s) => Ok(path.join(s)),
                Err(..) => Err(internal("cannot process path in git with a non \
                                         unicode filename")),
            }
        }
    }

    fn list_files_walk(&self, pkg: &Package, filter: &mut FnMut(&Path) -> bool)
                       -> CargoResult<Vec<PathBuf>> {
        let mut ret = Vec::new();
        for pkg in self.packages.iter().filter(|p| *p == pkg) {
            let loc = pkg.root();
            try!(PathSource::walk(loc, &mut ret, true, filter));
        }
        return Ok(ret);
    }

    fn walk(path: &Path, ret: &mut Vec<PathBuf>,
            is_root: bool, filter: &mut FnMut(&Path) -> bool) -> CargoResult<()>
    {
        if !fs::metadata(&path).map(|m| m.is_dir()).unwrap_or(false) {
            if (*filter)(path) {
                ret.push(path.to_path_buf());
            }
            return Ok(())
        }
        // Don't recurse into any sub-packages that we have
        if !is_root && fs::metadata(&path.join("Cargo.toml")).is_ok() {
            return Ok(())
        }
        for dir in try!(fs::read_dir(path)) {
            let dir = try!(dir).path();
            let name = dir.file_name().and_then(|s| s.to_str());
            // Skip dotfile directories
            if name.map(|s| s.starts_with(".")) == Some(true) {
                continue
            } else if is_root {
                // Skip cargo artifacts
                match name {
                    Some("target") | Some("Cargo.lock") => continue,
                    _ => {}
                }
            }
            try!(PathSource::walk(&dir, ret, false, filter));
        }
        return Ok(())
    }
}

impl<'cfg> Debug for PathSource<'cfg> {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        write!(f, "the paths source")
    }
}

impl<'cfg> Registry for PathSource<'cfg> {
    fn query(&mut self, dep: &Dependency) -> CargoResult<Vec<Summary>> {
        self.packages.query(dep)
    }
}

impl<'cfg> Source for PathSource<'cfg> {
    fn update(&mut self) -> CargoResult<()> {
        if !self.updated {
            let packages = try!(self.read_packages());
            self.packages.extend(packages.into_iter());
            self.updated = true;
        }

        Ok(())
    }

    fn download(&mut self, _: &[PackageId])  -> CargoResult<()>{
        // TODO: assert! that the PackageId is contained by the source
        Ok(())
    }

    fn get(&self, ids: &[PackageId]) -> CargoResult<Vec<Package>> {
        trace!("getting packages; ids={:?}", ids);

        Ok(self.packages.iter()
           .filter(|pkg| ids.iter().any(|id| pkg.package_id() == id))
           .map(|pkg| pkg.clone())
           .collect())
    }

    fn fingerprint(&self, pkg: &Package) -> CargoResult<String> {
        if !self.updated {
            return Err(internal_error("BUG: source was not updated", ""));
        }

        let mut max = FileTime::zero();
        let mut max_path = PathBuf::from("");
        for file in try!(self.list_files(pkg)) {
            // An fs::stat error here is either because path is a
            // broken symlink, a permissions error, or a race
            // condition where this path was rm'ed - either way,
            // we can ignore the error and treat the path's mtime
            // as 0.
            let mtime = fs::metadata(&file).map(|meta| {
                FileTime::from_last_modification_time(&meta)
            }).unwrap_or(FileTime::zero());
            warn!("{} {}", mtime, file.display());
            if mtime > max {
                max = mtime;
                max_path = file;
            }
        }
        trace!("fingerprint {}: {}", self.path.display(), max);
        Ok(format!("{} ({})", max, max_path.display()))
    }
}
<|endoftext|>


<commit_before><commit_msg>Use resiter::IterInnerOkOrElse instead of libimagerror version<commit_after><|endoftext|>


<commit_before><commit_msg>feature(io) is now feature(old_io)<commit_after><|endoftext|>


<commit_before><commit_msg>nbt: Small fix for `Display` implementation.<commit_after><|endoftext|>


<commit_before><commit_msg>New test for `cargo rustc --crate-type` with dependency<commit_after><|endoftext|>


<commit_before><commit_msg>Add an example of counting points<commit_after>//! Counts the number of points in a las file.

extern crate las;

use las::Reader;

fn main() {
    let path = std::env::args().skip(1).next().expect(
        "Must provide a path to a las file",
    );
    let mut reader = Reader::from_path(path).expect("Unable to open reader");
    let npoints = reader
        .points()
        .map(|p| p.expect("Unable to read point"))
        .count();
    println!("Number of points: {}", npoints);
}
<|endoftext|>


<commit_before><commit_msg>Add damping generator.<commit_after>use nalgebra::traits::scalar_op::ScalarMul;
use object::body::{Body, RigidBody, SoftBody};
use integration::integrator::Integrator;

pub struct BodyDamping<N, LV, AV, M, II> {
    priv damping_factor: N,
    priv objects:        ~[@mut Body<N, LV, AV, M, II>]
}

impl<N, LV, AV, M, II> BodyDamping<N, LV, AV, M, II> {
    pub fn new(damping_factor: N) -> BodyDamping<N, LV, AV, M, II> {
        BodyDamping {
            damping_factor: damping_factor,
            objects:        ~[]
        }
    }
}

impl<N: Clone, LV: Clone + ScalarMul<N>, AV: Clone + ScalarMul<N>, M: Clone, II: Clone>
Integrator<N, Body<N, LV, AV, M, II>> for BodyDamping<N, LV, AV, M, II> {
    fn add(&mut self, o: @mut Body<N, LV, AV, M, II>) {
        self.objects.push(o.clone());
    }

    fn remove(&mut self, _: @mut Body<N, LV, AV, M, II>) {
        fail!("Not yet implemented.");
    }

    fn update(&mut self, _: N) {
        for &o in self.objects.iter() {
            match *o {
                RigidBody(rb) => {
                    let new_lin = rb.lin_vel().scalar_mul(&self.damping_factor);
                    rb.set_lin_vel(new_lin);
                    let new_ang = rb.ang_vel().scalar_mul(&self.damping_factor);
                    rb.set_ang_vel(new_ang);
                },
                SoftBody(_) => {
                    fail!("Not yet implemented.")
                }
            }
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Add regression test for #66757<commit_after>// Regression test for #66757
//
// Test than when you have a `!` value (e.g., the local variable
// never) and an uninferred variable (here the argument to `From`) it
// doesn't fallback to `()` but rather `!`.
//
// run-pass

#![feature(never_type)]

// FIXME(#67225) -- this should be true even without the fallback gate.
#![feature(never_type_fallback)]

struct E;

impl From<!> for E {
    fn from(_: !) -> E {
        E
    }
}

#[allow(unreachable_code)]
#[allow(dead_code)]
fn foo(never: !) {
    <E as From<!>>::from(never);  // Ok
    <E as From<_>>::from(never);  // Inference fails here
}

fn main() { }
<|endoftext|>


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

#[fundamental] //~ ERROR the `#[fundamental]` attribute is an experimental feature
struct Fundamental;

fn main() { }
<|endoftext|>


<commit_before><commit_msg>Auto merge of #9515 - pickfire:patch-1, r=ehuss<commit_after><|endoftext|>


<commit_before><commit_msg>Arc1 code added<commit_after><|endoftext|>


<commit_before><commit_msg>add a test case for issue #32031<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.

// compile-flags: -C no-prepopulate-passes

#![crate_type = "lib"]

#[no_mangle]
pub struct F32(f32);

// CHECK: define float @add_newtype_f32(float, float)
#[inline(never)]
#[no_mangle]
pub fn add_newtype_f32(a: F32, b: F32) -> F32 {
    F32(a.0 + b.0)
}

#[no_mangle]
pub struct F64(f64);

// CHECK: define double @add_newtype_f64(double, double)
#[inline(never)]
#[no_mangle]
pub fn add_newtype_f64(a: F64, b: F64) -> F64 {
    F64(a.0 + b.0)
}
<|endoftext|>


<commit_before><commit_msg>Add xfailed test for #3979<commit_after>// xfail-test
trait Positioned {
  fn SetX(int);
}

trait Movable: Positioned {
  fn translate(dx: int) {
    self.SetX(self.X() + dx);
  }
}

fn main() {}
<|endoftext|>


<commit_before><commit_msg>Add validation layer for FPS, and full dump at application debug level 2 and above<commit_after><|endoftext|>


<commit_before><commit_msg>Rationalise names ending _raw to starting raw_ in Vulkan renderer<commit_after><|endoftext|>


<commit_before><commit_msg>add log message on socket disconnect<commit_after><|endoftext|>


<commit_before><commit_msg>Fix imag-mail to list from appropriate collection<commit_after><|endoftext|>


<commit_before>#![crate_type="staticlib"]
#![feature(alloc)]
#![feature(allocator)]
#![feature(arc_counts)]
#![feature(augmented_assignments)]
#![feature(asm)]
#![feature(box_syntax)]
#![feature(collections)]
#![feature(const_fn)]
#![feature(core_intrinsics)]
#![feature(core_str_ext)]
#![feature(core_slice_ext)]
#![feature(fnbox)]
#![feature(fundamental)]
#![feature(lang_items)]
#![feature(op_assign_traits)]
#![feature(unboxed_closures)]
#![feature(unsafe_no_drop_flag)]
#![feature(unwind_attributes)]
#![feature(vec_push_all)]
#![feature(zero_one)]
#![no_std]

#[macro_use]
extern crate alloc;

#[macro_use]
extern crate collections;

extern crate system;

use acpi::Acpi;

use alloc::boxed::Box;

use collections::string::{String, ToString};
use collections::vec::Vec;

use core::cell::UnsafeCell;
use core::{ptr, mem, usize};
use core::slice::SliceExt;

use common::event::{self, EVENT_KEY, EventOption};
use common::memory;
use common::paging::Page;
use common::time::Duration;

use drivers::pci;
use drivers::io::{Io, Pio};
use drivers::ps2::*;
use drivers::rtc::*;
use drivers::serial::*;

use env::Environment;

use graphics::display;

use scheduler::{Context, Regs, TSS};
use scheduler::context::context_switch;

use schemes::Url;
use schemes::context::*;
use schemes::debug::*;
use schemes::display::*;
use schemes::interrupt::*;
use schemes::memory::*;

use syscall::execute::execute;
use syscall::handle::*;

pub use system::externs::*;

/// Common std-like functionality
#[macro_use]
pub mod common;
#[macro_use]
pub mod macros;
/// Allocation
pub mod alloc_system;
/// ACPI
pub mod acpi;
/// Disk drivers
pub mod disk;
/// Various drivers
pub mod drivers;
/// Environment
pub mod env;
/// Filesystems
pub mod fs;
/// Various graphical methods
pub mod graphics;
/// Panic
pub mod panic;
/// Schemes
pub mod schemes;
/// Scheduling
pub mod scheduler;
/// Sync primatives
pub mod sync;
/// System calls
pub mod syscall;
/// USB input/output
pub mod usb;

pub static mut TSS_PTR: Option<&'static mut TSS> = None;
pub static mut ENV_PTR: Option<&'static mut Environment> = None;

pub fn env() -> &'static Environment {
    unsafe {
        match ENV_PTR {
            Some(&mut ref p) => p,
            None => unreachable!(),
        }
    }
}

/// Pit duration
static PIT_DURATION: Duration = Duration {
    secs: 0,
    nanos: 2250286,
};

/// Idle loop (active while idle)
unsafe fn idle_loop() {
    loop {
        asm!("cli" : : : : "intel", "volatile");

        let mut halt = true;

        for i in env().contexts.lock().iter().skip(1) {
            if i.interrupted {
                halt = false;
                break;
            }
        }

        if halt {
            asm!("sti" : : : : "intel", "volatile");
            asm!("hlt" : : : : "intel", "volatile");
        } else {
            asm!("sti" : : : : "intel", "volatile");
        }

        context_switch(false);
    }
}

/// Event poll loop
fn poll_loop() {
    loop {
        env().on_poll();

        unsafe { context_switch(false) };
    }
}

/// Event loop
fn event_loop() {
    {
        let mut console = env().console.lock();
        console.instant = false;
    }

    let mut cmd = String::new();
    loop {
        loop {
            let mut console = env().console.lock();
            match env().events.lock().pop_front() {
                Some(event) => {
                    if console.draw {
                        match event.to_option() {
                            EventOption::Key(key_event) => {
                                if key_event.pressed {
                                    match key_event.scancode {
                                        event::K_F2 => {
                                            console.draw = false;
                                        }
                                        event::K_BKSP => if !cmd.is_empty() {
                                            console.write(&[8]);
                                            cmd.pop();
                                        },
                                        _ => match key_event.character {
                                            '\0' => (),
                                            '\n' => {
                                                console.command = Some(cmd.clone());

                                                cmd.clear();
                                                console.write(&[10]);
                                            }
                                            _ => {
                                                cmd.push(key_event.character);
                                                console.write(&[key_event.character as u8]);
                                            }
                                        },
                                    }
                                }
                            }
                            _ => (),
                        }
                    } else {
                        if event.code == EVENT_KEY && event.b as u8 == event::K_F1 && event.c > 0 {
                            console.draw = true;
                            console.redraw = true;
                        } else {
                            // TODO: Magical orbital hack
                        }
                    }
                }
                None => break,
            }
        }

        {
            let mut console = env().console.lock();
            console.instant = false;
            if console.draw && console.redraw {
                console.redraw = false;
                console.display.flip();
            }
        }

        unsafe { context_switch(false) };
    }
}

static BSS_TEST_ZERO: usize = 0;
static BSS_TEST_NONZERO: usize = usize::MAX;

/// Initialize kernel
unsafe fn init(tss_data: usize) {

    // Test
    assume!(true);

    // Zero BSS, this initializes statics that are set to 0
    {
        extern {
            static mut __bss_start: u8;
            static mut __bss_end: u8;
        }

        let start_ptr = &mut __bss_start;
        let end_ptr = &mut __bss_end;

        if start_ptr as *const _ as usize <= end_ptr as *const _ as usize {
            let size = end_ptr as *const _ as usize - start_ptr as *const _ as usize;
            memset(start_ptr, 0, size);
        }

        assert_eq!(BSS_TEST_ZERO, 0);
        assert_eq!(BSS_TEST_NONZERO, usize::MAX);
    }

    // Setup paging, this allows for memory allocation
    Page::init();
    memory::cluster_init();
    // Unmap first page to catch null pointer errors (after reading memory map)
    Page::new(0).unmap();

    TSS_PTR = Some(&mut *(tss_data as *mut TSS));
    ENV_PTR = Some(&mut *Box::into_raw(Environment::new()));

    match ENV_PTR {
        Some(ref mut env) => {
            env.contexts.lock().push(Context::root());
            env.console.lock().draw = true;

            debug!("Redox {} bits\n", mem::size_of::<usize>() * 8);

            if let Some(acpi) = Acpi::new() {
                env.schemes.push(UnsafeCell::new(acpi));
            }

            *(env.clock_realtime.lock()) = Rtc::new().time();

            env.schemes.push(UnsafeCell::new(Ps2::new()));
            env.schemes.push(UnsafeCell::new(Serial::new(0x3F8, 0x4)));

            pci::pci_init(env);

            env.schemes.push(UnsafeCell::new(DebugScheme::new()));
            env.schemes.push(UnsafeCell::new(box DisplayScheme));
            env.schemes.push(UnsafeCell::new(box ContextScheme));
            env.schemes.push(UnsafeCell::new(box InterruptScheme));
            env.schemes.push(UnsafeCell::new(box MemoryScheme));

            Context::spawn("kpoll".to_string(),
            box move || {
                poll_loop();
            });

            Context::spawn("kevent".to_string(),
            box move || {
                event_loop();
            });

            env.contexts.lock().enabled = true;

            Context::spawn("kinit".to_string(),
            box move || {
                {
                    let wd_c = "file:/\0";
                    do_sys_chdir(wd_c.as_ptr());

                    let stdio_c = "debug:\0";
                    do_sys_open(stdio_c.as_ptr(), 0);
                    do_sys_open(stdio_c.as_ptr(), 0);
                    do_sys_open(stdio_c.as_ptr(), 0);
                }

                execute(Url::from_str("file:/apps/init/main.bin"), Vec::new());
                debug!("INIT: Failed to execute\n");

                loop {
                    context_switch(false);
                }
            });
        },
        None => unreachable!(),
    }
}

#[cold]
#[inline(never)]
#[no_mangle]
/// Take regs for kernel calls and exceptions
pub extern "cdecl" fn kernel(interrupt: usize, mut regs: &mut Regs) {
    macro_rules! exception_inner {
        ($name:expr) => ({
            {
                let contexts = ::env().contexts.lock();
                if let Some(context) = contexts.current() {
                    debugln!("PID {}: {}", context.pid, context.name);
                }
            }

            debugln!("  INT {:X}: {}", interrupt, $name);
            debugln!("    CS:  {:08X}    IP:  {:08X}    FLG: {:08X}", regs.cs, regs.ip, regs.flags);
            debugln!("    SS:  {:08X}    SP:  {:08X}    BP:  {:08X}", regs.ss, regs.sp, regs.bp);
            debugln!("    AX:  {:08X}    BX:  {:08X}    CX:  {:08X}    DX:  {:08X}", regs.ax, regs.bx, regs.cx, regs.dx);
            debugln!("    DI:  {:08X}    SI:  {:08X}", regs.di, regs.di);

            let cr0: usize;
            let cr2: usize;
            let cr3: usize;
            let cr4: usize;
            unsafe {
                asm!("mov $0, cr0" : "=r"(cr0) : : : "intel", "volatile");
                asm!("mov $0, cr2" : "=r"(cr2) : : : "intel", "volatile");
                asm!("mov $0, cr3" : "=r"(cr3) : : : "intel", "volatile");
                asm!("mov $0, cr4" : "=r"(cr4) : : : "intel", "volatile");
            }
            debugln!("    CR0: {:08X}    CR2: {:08X}    CR3: {:08X}    CR4: {:08X}", cr0, cr2, cr3, cr4);

            let sp = regs.sp as *const u32;
            for y in -15..16 {
                debug!("    {:>3}:", y * 8 * 4);
                for x in 0..8 {
                    debug!(" {:08X}", unsafe { ptr::read(sp.offset(-(x + y * 8))) });
                }
                debug!("\n");
            }
        })
    };

    macro_rules! exception {
        ($name:expr) => ({
            exception_inner!($name);

            loop {
                do_sys_exit(usize::MAX);
            }
        })
    };

    macro_rules! exception_error {
        ($name:expr) => ({
            let error = regs.ip;
            regs.ip = regs.cs;
            regs.cs = regs.flags;
            regs.flags = regs.sp;
            regs.sp = regs.ss;
            regs.ss = 0;
            //regs.ss = regs.error;

            exception_inner!($name);
            debugln!("    ERR: {:08X}", error);

            loop {
                do_sys_exit(usize::MAX);
            }
        })
    };

    if interrupt >= 0x20 && interrupt < 0x30 {
        if interrupt >= 0x28 {
            Pio::<u8>::new(0xA0).write(0x20);
        }

        Pio::<u8>::new(0x20).write(0x20);
    }

    //Do not catch init interrupt
    if interrupt < 0xFF {
        env().interrupts.lock()[interrupt as usize] += 1;
    }

    match interrupt {
        0x20 => {
            {
                let mut clock_monotonic = env().clock_monotonic.lock();
                *clock_monotonic = *clock_monotonic + PIT_DURATION;
            }
            {
                let mut clock_realtime = env().clock_realtime.lock();
                *clock_realtime = *clock_realtime + PIT_DURATION;
            }

            let switch = {
                let mut contexts = ::env().contexts.lock();
                if let Some(mut context) = contexts.current_mut() {
                    context.slices -= 1;
                    context.slice_total += 1;
                    context.slices == 0
                } else {
                    false
                }
            };

            if switch {
                unsafe { context_switch(true) };
            }
        }
        i @ 0x21 ... 0x2F => env().on_irq(i as u8 - 0x20),
        0x80 => if !syscall_handle(regs) {
            exception!("Unknown Syscall");
        },
        0xFF => {
            unsafe {
                init(regs.ax);
                idle_loop();
            }
        },
        0x0 => exception!("Divide by zero exception"),
        0x1 => exception!("Debug exception"),
        0x2 => exception!("Non-maskable interrupt"),
        0x3 => exception!("Breakpoint exception"),
        0x4 => exception!("Overflow exception"),
        0x5 => exception!("Bound range exceeded exception"),
        0x6 => exception!("Invalid opcode exception"),
        0x7 => exception!("Device not available exception"),
        0x8 => exception_error!("Double fault"),
        0x9 => exception!("Coprocessor Segment Overrun"), // legacy
        0xA => exception_error!("Invalid TSS exception"),
        0xB => exception_error!("Segment not present exception"),
        0xC => exception_error!("Stack-segment fault"),
        0xD => exception_error!("General protection fault"),
        0xE => exception_error!("Page fault"),
        0x10 => exception!("x87 floating-point exception"),
        0x11 => exception_error!("Alignment check exception"),
        0x12 => exception!("Machine check exception"),
        0x13 => exception!("SIMD floating-point exception"),
        0x14 => exception!("Virtualization exception"),
        0x1E => exception_error!("Security exception"),
        _ => exception!("Unknown Interrupt"),
    }
}

#[test]
fn get_slice_test() {
    let array = [1, 2, 3, 4, 5];
    assert_eq!(array.get_slice(2, None), array[2..]);
    assert_eq!(array.get_slice(2, array.len()), array[2..array.len()]);
    assert_eq!(array.get_slice(None, 2), array[..2]);
    assert_eq!(array.get_slice(0, 2), array[0..2]);
    assert_eq!(array.get_slice(1, array.len()), array[1..array.len()]);
    assert_eq!(array.get_slice(1, array.len() + 1), array[1..array.len()]);
    assert_eq!(array.get_slice(array.len(), array.len()),
               array[array.len()..array.len()]);
    assert_eq!(array.get_slice(array.len() + 2, array.len() + 2),
               array[array.len()..array.len()]);
}
<commit_msg>Format idle loop asm<commit_after>#![crate_type="staticlib"]
#![feature(alloc)]
#![feature(allocator)]
#![feature(arc_counts)]
#![feature(augmented_assignments)]
#![feature(asm)]
#![feature(box_syntax)]
#![feature(collections)]
#![feature(const_fn)]
#![feature(core_intrinsics)]
#![feature(core_str_ext)]
#![feature(core_slice_ext)]
#![feature(fnbox)]
#![feature(fundamental)]
#![feature(lang_items)]
#![feature(op_assign_traits)]
#![feature(unboxed_closures)]
#![feature(unsafe_no_drop_flag)]
#![feature(unwind_attributes)]
#![feature(vec_push_all)]
#![feature(zero_one)]
#![no_std]

#[macro_use]
extern crate alloc;

#[macro_use]
extern crate collections;

extern crate system;

use acpi::Acpi;

use alloc::boxed::Box;

use collections::string::{String, ToString};
use collections::vec::Vec;

use core::cell::UnsafeCell;
use core::{ptr, mem, usize};
use core::slice::SliceExt;

use common::event::{self, EVENT_KEY, EventOption};
use common::memory;
use common::paging::Page;
use common::time::Duration;

use drivers::pci;
use drivers::io::{Io, Pio};
use drivers::ps2::*;
use drivers::rtc::*;
use drivers::serial::*;

use env::Environment;

use graphics::display;

use scheduler::{Context, Regs, TSS};
use scheduler::context::context_switch;

use schemes::Url;
use schemes::context::*;
use schemes::debug::*;
use schemes::display::*;
use schemes::interrupt::*;
use schemes::memory::*;

use syscall::execute::execute;
use syscall::handle::*;

pub use system::externs::*;

/// Common std-like functionality
#[macro_use]
pub mod common;
#[macro_use]
pub mod macros;
/// Allocation
pub mod alloc_system;
/// ACPI
pub mod acpi;
/// Disk drivers
pub mod disk;
/// Various drivers
pub mod drivers;
/// Environment
pub mod env;
/// Filesystems
pub mod fs;
/// Various graphical methods
pub mod graphics;
/// Panic
pub mod panic;
/// Schemes
pub mod schemes;
/// Scheduling
pub mod scheduler;
/// Sync primatives
pub mod sync;
/// System calls
pub mod syscall;
/// USB input/output
pub mod usb;

pub static mut TSS_PTR: Option<&'static mut TSS> = None;
pub static mut ENV_PTR: Option<&'static mut Environment> = None;

pub fn env() -> &'static Environment {
    unsafe {
        match ENV_PTR {
            Some(&mut ref p) => p,
            None => unreachable!(),
        }
    }
}

/// Pit duration
static PIT_DURATION: Duration = Duration {
    secs: 0,
    nanos: 2250286,
};

/// Idle loop (active while idle)
unsafe fn idle_loop() {
    loop {
        asm!("cli" : : : : "intel", "volatile");

        let mut halt = true;

        for i in env().contexts.lock().iter().skip(1) {
            if i.interrupted {
                halt = false;
                break;
            }
        }

        if halt {
            asm!("sti
                  hlt"
                  :
                  :
                  :
                  : "intel", "volatile");
        } else {
            asm!("sti"
                :
                :
                :
                : "intel", "volatile");
        }

        context_switch(false);
    }
}

/// Event poll loop
fn poll_loop() {
    loop {
        env().on_poll();

        unsafe { context_switch(false) };
    }
}

/// Event loop
fn event_loop() {
    {
        let mut console = env().console.lock();
        console.instant = false;
    }

    let mut cmd = String::new();
    loop {
        loop {
            let mut console = env().console.lock();
            match env().events.lock().pop_front() {
                Some(event) => {
                    if console.draw {
                        match event.to_option() {
                            EventOption::Key(key_event) => {
                                if key_event.pressed {
                                    match key_event.scancode {
                                        event::K_F2 => {
                                            console.draw = false;
                                        }
                                        event::K_BKSP => if !cmd.is_empty() {
                                            console.write(&[8]);
                                            cmd.pop();
                                        },
                                        _ => match key_event.character {
                                            '\0' => (),
                                            '\n' => {
                                                console.command = Some(cmd.clone());

                                                cmd.clear();
                                                console.write(&[10]);
                                            }
                                            _ => {
                                                cmd.push(key_event.character);
                                                console.write(&[key_event.character as u8]);
                                            }
                                        },
                                    }
                                }
                            }
                            _ => (),
                        }
                    } else {
                        if event.code == EVENT_KEY && event.b as u8 == event::K_F1 && event.c > 0 {
                            console.draw = true;
                            console.redraw = true;
                        } else {
                            // TODO: Magical orbital hack
                        }
                    }
                }
                None => break,
            }
        }

        {
            let mut console = env().console.lock();
            console.instant = false;
            if console.draw && console.redraw {
                console.redraw = false;
                console.display.flip();
            }
        }

        unsafe { context_switch(false) };
    }
}

static BSS_TEST_ZERO: usize = 0;
static BSS_TEST_NONZERO: usize = usize::MAX;

/// Initialize kernel
unsafe fn init(tss_data: usize) {

    // Test
    assume!(true);

    // Zero BSS, this initializes statics that are set to 0
    {
        extern {
            static mut __bss_start: u8;
            static mut __bss_end: u8;
        }

        let start_ptr = &mut __bss_start;
        let end_ptr = &mut __bss_end;

        if start_ptr as *const _ as usize <= end_ptr as *const _ as usize {
            let size = end_ptr as *const _ as usize - start_ptr as *const _ as usize;
            memset(start_ptr, 0, size);
        }

        assert_eq!(BSS_TEST_ZERO, 0);
        assert_eq!(BSS_TEST_NONZERO, usize::MAX);
    }

    // Setup paging, this allows for memory allocation
    Page::init();
    memory::cluster_init();
    // Unmap first page to catch null pointer errors (after reading memory map)
    Page::new(0).unmap();

    TSS_PTR = Some(&mut *(tss_data as *mut TSS));
    ENV_PTR = Some(&mut *Box::into_raw(Environment::new()));

    match ENV_PTR {
        Some(ref mut env) => {
            env.contexts.lock().push(Context::root());
            env.console.lock().draw = true;

            debug!("Redox {} bits\n", mem::size_of::<usize>() * 8);

            if let Some(acpi) = Acpi::new() {
                env.schemes.push(UnsafeCell::new(acpi));
            }

            *(env.clock_realtime.lock()) = Rtc::new().time();

            env.schemes.push(UnsafeCell::new(Ps2::new()));
            env.schemes.push(UnsafeCell::new(Serial::new(0x3F8, 0x4)));

            pci::pci_init(env);

            env.schemes.push(UnsafeCell::new(DebugScheme::new()));
            env.schemes.push(UnsafeCell::new(box DisplayScheme));
            env.schemes.push(UnsafeCell::new(box ContextScheme));
            env.schemes.push(UnsafeCell::new(box InterruptScheme));
            env.schemes.push(UnsafeCell::new(box MemoryScheme));

            Context::spawn("kpoll".to_string(),
            box move || {
                poll_loop();
            });

            Context::spawn("kevent".to_string(),
            box move || {
                event_loop();
            });

            env.contexts.lock().enabled = true;

            Context::spawn("kinit".to_string(),
            box move || {
                {
                    let wd_c = "file:/\0";
                    do_sys_chdir(wd_c.as_ptr());

                    let stdio_c = "debug:\0";
                    do_sys_open(stdio_c.as_ptr(), 0);
                    do_sys_open(stdio_c.as_ptr(), 0);
                    do_sys_open(stdio_c.as_ptr(), 0);
                }

                execute(Url::from_str("file:/apps/init/main.bin"), Vec::new());
                debug!("INIT: Failed to execute\n");

                loop {
                    context_switch(false);
                }
            });
        },
        None => unreachable!(),
    }
}

#[cold]
#[inline(never)]
#[no_mangle]
/// Take regs for kernel calls and exceptions
pub extern "cdecl" fn kernel(interrupt: usize, mut regs: &mut Regs) {
    macro_rules! exception_inner {
        ($name:expr) => ({
            {
                let contexts = ::env().contexts.lock();
                if let Some(context) = contexts.current() {
                    debugln!("PID {}: {}", context.pid, context.name);
                }
            }

            debugln!("  INT {:X}: {}", interrupt, $name);
            debugln!("    CS:  {:08X}    IP:  {:08X}    FLG: {:08X}", regs.cs, regs.ip, regs.flags);
            debugln!("    SS:  {:08X}    SP:  {:08X}    BP:  {:08X}", regs.ss, regs.sp, regs.bp);
            debugln!("    AX:  {:08X}    BX:  {:08X}    CX:  {:08X}    DX:  {:08X}", regs.ax, regs.bx, regs.cx, regs.dx);
            debugln!("    DI:  {:08X}    SI:  {:08X}", regs.di, regs.di);

            let cr0: usize;
            let cr2: usize;
            let cr3: usize;
            let cr4: usize;
            unsafe {
                asm!("mov $0, cr0" : "=r"(cr0) : : : "intel", "volatile");
                asm!("mov $0, cr2" : "=r"(cr2) : : : "intel", "volatile");
                asm!("mov $0, cr3" : "=r"(cr3) : : : "intel", "volatile");
                asm!("mov $0, cr4" : "=r"(cr4) : : : "intel", "volatile");
            }
            debugln!("    CR0: {:08X}    CR2: {:08X}    CR3: {:08X}    CR4: {:08X}", cr0, cr2, cr3, cr4);

            let sp = regs.sp as *const u32;
            for y in -15..16 {
                debug!("    {:>3}:", y * 8 * 4);
                for x in 0..8 {
                    debug!(" {:08X}", unsafe { ptr::read(sp.offset(-(x + y * 8))) });
                }
                debug!("\n");
            }
        })
    };

    macro_rules! exception {
        ($name:expr) => ({
            exception_inner!($name);

            loop {
                do_sys_exit(usize::MAX);
            }
        })
    };

    macro_rules! exception_error {
        ($name:expr) => ({
            let error = regs.ip;
            regs.ip = regs.cs;
            regs.cs = regs.flags;
            regs.flags = regs.sp;
            regs.sp = regs.ss;
            regs.ss = 0;
            //regs.ss = regs.error;

            exception_inner!($name);
            debugln!("    ERR: {:08X}", error);

            loop {
                do_sys_exit(usize::MAX);
            }
        })
    };

    if interrupt >= 0x20 && interrupt < 0x30 {
        if interrupt >= 0x28 {
            Pio::<u8>::new(0xA0).write(0x20);
        }

        Pio::<u8>::new(0x20).write(0x20);
    }

    //Do not catch init interrupt
    if interrupt < 0xFF {
        env().interrupts.lock()[interrupt as usize] += 1;
    }

    match interrupt {
        0x20 => {
            {
                let mut clock_monotonic = env().clock_monotonic.lock();
                *clock_monotonic = *clock_monotonic + PIT_DURATION;
            }
            {
                let mut clock_realtime = env().clock_realtime.lock();
                *clock_realtime = *clock_realtime + PIT_DURATION;
            }

            let switch = {
                let mut contexts = ::env().contexts.lock();
                if let Some(mut context) = contexts.current_mut() {
                    context.slices -= 1;
                    context.slice_total += 1;
                    context.slices == 0
                } else {
                    false
                }
            };

            if switch {
                unsafe { context_switch(true) };
            }
        }
        i @ 0x21 ... 0x2F => env().on_irq(i as u8 - 0x20),
        0x80 => if !syscall_handle(regs) {
            exception!("Unknown Syscall");
        },
        0xFF => {
            unsafe {
                init(regs.ax);
                idle_loop();
            }
        },
        0x0 => exception!("Divide by zero exception"),
        0x1 => exception!("Debug exception"),
        0x2 => exception!("Non-maskable interrupt"),
        0x3 => exception!("Breakpoint exception"),
        0x4 => exception!("Overflow exception"),
        0x5 => exception!("Bound range exceeded exception"),
        0x6 => exception!("Invalid opcode exception"),
        0x7 => exception!("Device not available exception"),
        0x8 => exception_error!("Double fault"),
        0x9 => exception!("Coprocessor Segment Overrun"), // legacy
        0xA => exception_error!("Invalid TSS exception"),
        0xB => exception_error!("Segment not present exception"),
        0xC => exception_error!("Stack-segment fault"),
        0xD => exception_error!("General protection fault"),
        0xE => exception_error!("Page fault"),
        0x10 => exception!("x87 floating-point exception"),
        0x11 => exception_error!("Alignment check exception"),
        0x12 => exception!("Machine check exception"),
        0x13 => exception!("SIMD floating-point exception"),
        0x14 => exception!("Virtualization exception"),
        0x1E => exception_error!("Security exception"),
        _ => exception!("Unknown Interrupt"),
    }
}

#[test]
fn get_slice_test() {
    let array = [1, 2, 3, 4, 5];
    assert_eq!(array.get_slice(2, None), array[2..]);
    assert_eq!(array.get_slice(2, array.len()), array[2..array.len()]);
    assert_eq!(array.get_slice(None, 2), array[..2]);
    assert_eq!(array.get_slice(0, 2), array[0..2]);
    assert_eq!(array.get_slice(1, array.len()), array[1..array.len()]);
    assert_eq!(array.get_slice(1, array.len() + 1), array[1..array.len()]);
    assert_eq!(array.get_slice(array.len(), array.len()),
               array[array.len()..array.len()]);
    assert_eq!(array.get_slice(array.len() + 2, array.len() + 2),
               array[array.len()..array.len()]);
}
<|endoftext|>


<commit_before><commit_msg>Rollup merge of #56661 - aelred:issue-55846, r=Mark-Simulacrum<commit_after>// run-pass

// Regression test for #55846, which once caused an ICE.

use std::marker::PhantomData;

struct Foo;

struct Bar<A> {
    a: PhantomData<A>,
}

impl Fooifier for Foo {
    type Assoc = Foo;
}

trait Fooifier {
    type Assoc;
}

trait Barifier<H> {
    fn barify();
}

impl<H> Barifier<H> for Bar<H> {
    fn barify() {
        println!("All correct!");
    }
}

impl Bar<<Foo as Fooifier>::Assoc> {
    fn this_shouldnt_crash() {
        <Self as Barifier<<Foo as Fooifier>::Assoc>>::barify();
    }
}

fn main() {
    Bar::<Foo>::this_shouldnt_crash();
}
<|endoftext|>


<commit_before><commit_msg>Okay, the error is now more apparent.<commit_after><|endoftext|>


<commit_before><commit_msg>Sort by Unit Names Previously, I was sorting units by their path. This change will sort by names of the units instead.<commit_after><|endoftext|>


<commit_before><commit_msg>Failed attempt to add an explicit pipeline barrier to fix the rendering<commit_after><|endoftext|>


<commit_before><commit_msg>Replace all VK_NULL_HANDLE_MUT() with ptr::null_mut() for consistency with uses of ptr::null()<commit_after><|endoftext|>


<commit_before><commit_msg>Assign a fence for each command buffer to avoid creating and destroying one each time execute_now() is invoked<commit_after><|endoftext|>


<commit_before><commit_msg>Review and tidy the RenderVk fields and construction<commit_after><|endoftext|>


<commit_before><commit_msg>clear test<commit_after><|endoftext|>


<commit_before><commit_msg>Fix test: Check whether in cache, then get, then check again<commit_after><|endoftext|>


<commit_before><commit_msg>Add regression test for #73137<commit_after>// Regression test for <https://github.com/rust-lang/rust/issues/73137>

// run-pass
// edition:2018

#![allow(dead_code)]
#![feature(wake_trait)]
use std::future::Future;
use std::task::{Waker, Wake, Context};
use std::sync::Arc;

struct DummyWaker;
impl Wake for DummyWaker {
    fn wake(self: Arc<Self>) {}
}

struct Foo {
    a: usize,
    b: &'static u32,
}

#[inline(never)]
fn nop<T>(_: T) {}

fn main() {
    let mut fut = Box::pin(async {
        let action = Foo {
            b: &42,
            a: async { 0 }.await,
        };

        // An error in the generator transform caused `b` to be overwritten with `a` when `b` was
        // borrowed.
        nop(&action.b);
        assert_ne!(0usize, unsafe { std::mem::transmute(action.b) });

        async {}.await;
    });
    let waker = Waker::from(Arc::new(DummyWaker));
    let mut cx = Context::from_waker(&waker);
    let _ = fut.as_mut().poll(&mut cx);
}
<|endoftext|>


<commit_before><commit_msg>chore: unit test<commit_after><|endoftext|>


<commit_before>use std::error::Error;
use std::fmt::Debug;
use std::fmt::Display;
use std::fmt::Formatter;
use std::fmt::Error as FmtError;
use std::clone::Clone;
use std::convert::From;

use std::io::Error as IOError;

#[derive(Clone)]
pub enum StoreErrorType {
    Unknown,
    IdNotFound,
    OutOfMemory,
    // maybe more
}

impl From<StoreErrorType> for String {

    fn from(e: StoreErrorType) -> String {
        String::from(&e)
    }

}

impl<'a> From<&'a StoreErrorType> for String {

    fn from(e: &'a StoreErrorType) -> String {
        match e {
            &StoreErrorType::Unknown     => String::from("<Unknown>"),
            &StoreErrorType::IdNotFound  => String::from("ID not found"),
            &StoreErrorType::OutOfMemory => String::from("Out of Memory"),
        }
    }

}

impl Debug for StoreErrorType {

    fn fmt(&self, fmt: &mut Formatter) -> Result<(), FmtError> {
        let s : String = self.into();
        try!(write!(fmt, "{:?}", s));
        Ok(())
    }

}

impl Display for StoreErrorType {

    fn fmt(&self, fmt: &mut Formatter) -> Result<(), FmtError> {
        let s : String = self.into();
        try!(write!(fmt, "{}", s));
        Ok(())
    }

}

pub struct StoreError {
    err_type: StoreErrorType,
    expl: Option<&'static str>,
    cause: Option<Box<Error>>,
}

impl StoreError {

    pub fn new() -> StoreError {
        StoreError {
            err_type: StoreErrorType::Unknown,
            expl:  None,
            cause: None,
        }
    }

    pub fn err_type(&self) -> StoreErrorType {
        self.err_type.clone()
    }

    pub fn with_type(mut self, t: StoreErrorType) -> StoreError {
        self.err_type = t;
        self
    }

    pub fn with_expl(mut self, e: &'static str) -> StoreError {
        self.expl = Some(e);
        self
    }

    pub fn with_cause(mut self, e: Box<Error>) -> StoreError {
        self.cause = Some(e);
        self
    }

}

impl Debug for StoreError {

    fn fmt(&self, fmt: &mut Formatter) -> Result<(), FmtError> {
        try!(write!(fmt, "[{:?}]: {:?}, caused: {:?}",
                    self.err_type, self.expl, self.cause));
        Ok(())
    }

}

impl Display for StoreError {

    fn fmt(&self, fmt: &mut Formatter) -> Result<(), FmtError> {
        let e : String = self.err_type.clone().into();
        try!(write!(fmt, "[{}]: {}",
                    e,
                    self.expl.unwrap_or("")));
        Ok(())
    }

}

impl Error for StoreError {

    fn description(&self) -> &str {
        self.expl.unwrap_or("")
    }

    fn cause(&self) -> Option<&Error> {
        self.cause.as_ref().map(|e| &**e)
    }

}

<commit_msg>Pass error members on ::new()<commit_after>use std::error::Error;
use std::fmt::Debug;
use std::fmt::Display;
use std::fmt::Formatter;
use std::fmt::Error as FmtError;
use std::clone::Clone;
use std::convert::From;

use std::io::Error as IOError;

#[derive(Clone)]
pub enum StoreErrorType {
    Unknown,
    IdNotFound,
    OutOfMemory,
    // maybe more
}

impl From<StoreErrorType> for String {

    fn from(e: StoreErrorType) -> String {
        String::from(&e)
    }

}

impl<'a> From<&'a StoreErrorType> for String {

    fn from(e: &'a StoreErrorType) -> String {
        match e {
            &StoreErrorType::Unknown     => String::from("<Unknown>"),
            &StoreErrorType::IdNotFound  => String::from("ID not found"),
            &StoreErrorType::OutOfMemory => String::from("Out of Memory"),
        }
    }

}

impl Debug for StoreErrorType {

    fn fmt(&self, fmt: &mut Formatter) -> Result<(), FmtError> {
        let s : String = self.into();
        try!(write!(fmt, "{:?}", s));
        Ok(())
    }

}

impl Display for StoreErrorType {

    fn fmt(&self, fmt: &mut Formatter) -> Result<(), FmtError> {
        let s : String = self.into();
        try!(write!(fmt, "{}", s));
        Ok(())
    }

}

pub struct StoreError {
    err_type: StoreErrorType,
    expl: &'static str,
    cause: Option<Box<Error>>,
}

impl StoreError {

    pub fn new(errtype: StoreErrorType, expl: &'static str, cause: Option<Box<Error>>)
        -> StoreError
    {
        StoreError {
            err_type: errtype,
            expl:  expl,
            cause: cause,
        }
    }

    pub fn err_type(&self) -> StoreErrorType {
        self.err_type.clone()
    }

}

impl Debug for StoreError {

    fn fmt(&self, fmt: &mut Formatter) -> Result<(), FmtError> {
        try!(write!(fmt, "[{:?}]: {:?}, caused: {:?}",
                    self.err_type, self.expl, self.cause));
        Ok(())
    }

}

impl Display for StoreError {

    fn fmt(&self, fmt: &mut Formatter) -> Result<(), FmtError> {
        let e : String = self.err_type.clone().into();
        try!(write!(fmt, "[{}]: {}", e, self.expl));
        Ok(())
    }

}

impl Error for StoreError {

    fn description(&self) -> &str {
        self.expl
    }

    fn cause(&self) -> Option<&Error> {
        self.cause.as_ref().map(|e| &**e)
    }

}

<|endoftext|>


<commit_before><commit_msg>add example<commit_after>extern crate irc;

use irc::protocol::{Message, Body, IrcMessage};
use irc::protocol::command::PrivmsgCommand;

fn main() {

    let data = ":abc!abc@example.com PRIVMSG #rust :Ok, thanks guys. :)";
    let parsed_msg = Message::from_str(data).unwrap();

    let privmsg = PrivmsgCommand::new("#rust", "Ok, thanks guys. :)");
    let expected_msg = Message::new(Some("abc!abc@example.com"), Body::command(privmsg));

    assert_eq!(expected_msg, parsed_msg);

    println!("{}", expected_msg);
}
<|endoftext|>


<commit_before><commit_msg>Writing diagnostics for frame writing duration<commit_after><|endoftext|>