<commit_before><commit_msg>tests ~ add tests for new 'default_missing_value' configuration option<commit_after>use clap::{App, Arg};

#[test]
fn opt_missing() {
    let r = App::new("df")
        .arg(
            Arg::new("color")
                .long("color")
                .default_value("auto")
                .min_values(0)
                .require_equals(true)
                .default_missing_value("always"),
        )
        .try_get_matches_from(vec![""]);
    assert!(r.is_ok());
    let m = r.unwrap();
    assert!(m.is_present("color"));
    assert_eq!(m.value_of("color").unwrap(), "auto");
    assert_eq!(m.occurrences_of("color"), 0);
}

#[test]
fn opt_present_with_missing_value() {
    let r = App::new("df")
        .arg(
            Arg::new("color")
                .long("color")
                .default_value("auto")
                .min_values(0)
                .require_equals(true)
                .default_missing_value("always"),
        )
        .try_get_matches_from(vec!["", "--color"]);
    assert!(r.is_ok());
    let m = r.unwrap();
    assert!(m.is_present("color"));
    assert_eq!(m.value_of("color").unwrap(), "always");
    assert_eq!(m.occurrences_of("color"), 1);
}

#[test]
fn opt_present_with_value() {
    let r = App::new("df")
        .arg(
            Arg::new("color")
                .long("color")
                .default_value("auto")
                .min_values(0)
                .require_equals(true)
                .default_missing_value("always"),
        )
        .try_get_matches_from(vec!["", "--color=never"]);
    assert!(r.is_ok());
    let m = r.unwrap();
    assert!(m.is_present("color"));
    assert_eq!(m.value_of("color").unwrap(), "never");
    assert_eq!(m.occurrences_of("color"), 1);
}

// ToDO: [2020-05-20; rivy] test currently fails as empty values are still a work-in-progress (see <https://github.com/clap-rs/clap/pull/1587#issuecomment-631648788>)
// #[test]
// fn opt_present_with_empty_value() {
//     let r = App::new("df")
//         .arg(Arg::new("color").long("color")
//             .default_value("auto")
//             .min_values(0)
//             .require_equals(true)
//             .default_missing_value("always")
//         )
//         .try_get_matches_from(vec!["", "--color="]);
//     assert!(r.is_ok());
//     let m = r.unwrap();
//     assert!(m.is_present("color"));
//     assert_eq!(m.value_of("color").unwrap(), "");
//     assert_eq!(m.occurrences_of("color"), 1);
// }

//## `default_value`/`default_missing_value` non-interaction checks

#[test]
fn opt_default() {
    // assert no change to usual argument handling when adding default_missing_value()
    let r = App::new("app")
        .arg(
            Arg::from("-o [opt] 'some opt'")
                .default_value("default")
                .default_missing_value("default_missing"),
        )
        .try_get_matches_from(vec![""]);
    assert!(r.is_ok());
    let m = r.unwrap();
    assert!(m.is_present("o"));
    assert_eq!(m.value_of("o").unwrap(), "default");
}

#[test]
fn opt_default_user_override() {
    // assert no change to usual argument handling when adding default_missing_value()
    let r = App::new("app")
        .arg(
            Arg::from("-o [opt] 'some opt'")
                .default_value("default")
                .default_missing_value("default_missing"),
        )
        .try_get_matches_from(vec!["", "-o=value"]);
    assert!(r.is_ok());
    let m = r.unwrap();
    assert!(m.is_present("o"));
    assert_eq!(m.value_of("o").unwrap(), "value");
}
<|endoftext|>


<commit_before><commit_msg>also test div-by-minus-1<commit_after>#![feature(core_intrinsics)]
fn main() {
    // MIN/-1 cannot be represented
    unsafe { std::intrinsics::unchecked_div(i16::min_value(), -1); } //~ ERROR Overflow executing `unchecked_div`
}
<|endoftext|>


<commit_before><commit_msg>cleanup hascommand trait<commit_after><|endoftext|>


<commit_before><commit_msg>blank message<commit_after><|endoftext|>


<commit_before><commit_msg>add view.rs<commit_after><|endoftext|>


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

//! Sanity checking performed by rustbuild before actually executing anything.
//!
//! This module contains the implementation of ensuring that the build
//! environment looks reasonable before progressing. This will verify that
//! various programs like git and python exist, along with ensuring that all C
//! compilers for cross-compiling are found.
//!
//! In theory if we get past this phase it's a bug if a build fails, but in
//! practice that's likely not true!

use std::collections::HashSet;
use std::env;
use std::ffi::{OsStr, OsString};
use std::fs;
use std::process::Command;

use build_helper::output;

use Build;

pub fn check(build: &mut Build) {
    let mut checked = HashSet::new();
    let path = env::var_os("PATH").unwrap_or(OsString::new());
    // On Windows, quotes are invalid characters for filename paths, and if
    // one is present as part of the PATH then that can lead to the system
    // being unable to identify the files properly. See
    // https://github.com/rust-lang/rust/issues/34959 for more details.
    if cfg!(windows) {
        if path.to_string_lossy().contains("\"") {
            panic!("PATH contains invalid character '\"'");
        }
    }
    let mut need_cmd = |cmd: &OsStr| {
        if !checked.insert(cmd.to_owned()) {
            return
        }
        for path in env::split_paths(&path).map(|p| p.join(cmd)) {
            if fs::metadata(&path).is_ok() ||
               fs::metadata(path.with_extension("exe")).is_ok() {
                return
            }
        }
        panic!("\n\ncouldn't find required command: {:?}\n\n", cmd);
    };

    // If we've got a git directory we're gona need git to update
    // submodules and learn about various other aspects.
    if fs::metadata(build.src.join(".git")).is_ok() {
        need_cmd("git".as_ref());
    }

    // We need cmake, but only if we're actually building LLVM
    for host in build.config.host.iter() {
        if let Some(config) = build.config.target_config.get(host) {
            if config.llvm_config.is_some() {
                continue
            }
        }
        need_cmd("cmake".as_ref());
        if build.config.ninja {
            need_cmd("ninja".as_ref())
        }
        break
    }

    need_cmd("python".as_ref());

    // We're gonna build some custom C code here and there, host triples
    // also build some C++ shims for LLVM so we need a C++ compiler.
    for target in build.config.target.iter() {
        need_cmd(build.cc(target).as_ref());
        if let Some(ar) = build.ar(target) {
            need_cmd(ar.as_ref());
        }
    }
    for host in build.config.host.iter() {
        need_cmd(build.cxx(host).as_ref());
    }

    // Externally configured LLVM requires FileCheck to exist
    let filecheck = build.llvm_filecheck(&build.config.build);
    if !filecheck.starts_with(&build.out) && !filecheck.exists() {
        panic!("filecheck executable {:?} does not exist", filecheck);
    }

    for target in build.config.target.iter() {
        // Either can't build or don't want to run jemalloc on these targets
        if target.contains("rumprun") ||
           target.contains("bitrig") ||
           target.contains("openbsd") ||
           target.contains("msvc") {
            build.config.use_jemalloc = false;
        }

        // Can't compile for iOS unless we're on OSX
        if target.contains("apple-ios") &&
           !build.config.build.contains("apple-darwin") {
            panic!("the iOS target is only supported on OSX");
        }

        // Make sure musl-root is valid if specified
        if target.contains("musl") && !target.contains("mips") {
            match build.config.musl_root {
                Some(ref root) => {
                    if fs::metadata(root.join("lib/libc.a")).is_err() {
                        panic!("couldn't find libc.a in musl dir: {}",
                               root.join("lib").display());
                    }
                    if fs::metadata(root.join("lib/libunwind.a")).is_err() {
                        panic!("couldn't find libunwind.a in musl dir: {}",
                               root.join("lib").display());
                    }
                }
                None => {
                    panic!("when targeting MUSL the build.musl-root option \
                            must be specified in config.toml")
                }
            }
        }

        if target.contains("msvc") {
            // There are three builds of cmake on windows: MSVC, MinGW, and
            // Cygwin. The Cygwin build does not have generators for Visual
            // Studio, so detect that here and error.
            let out = output(Command::new("cmake").arg("--help"));
            if !out.contains("Visual Studio") {
                panic!("
cmake does not support Visual Studio generators.

This is likely due to it being an msys/cygwin build of cmake,
rather than the required windows version, built using MinGW
or Visual Studio.

If you are building under msys2 try installing the mingw-w64-x86_64-cmake
package instead of cmake:

$ pacman -R cmake && pacman -S mingw-w64-x86_64-cmake
");
            }
        }

        if target.contains("arm-linux-android") {
            need_cmd("adb".as_ref());
        }
    }

    for host in build.flags.host.iter() {
        if !build.config.host.contains(host) {
            panic!("specified host `{}` is not in the ./configure list", host);
        }
    }
    for target in build.flags.target.iter() {
        if !build.config.target.contains(target) {
            panic!("specified target `{}` is not in the ./configure list",
                   target);
        }
    }

    let run = |cmd: &mut Command| {
        cmd.output().map(|output| {
            String::from_utf8_lossy(&output.stdout)
                   .lines().next().unwrap()
                   .to_string()
        })
    };
    build.gdb_version = run(Command::new("gdb").arg("--version")).ok();
    build.lldb_version = run(Command::new("lldb").arg("--version")).ok();
    if build.lldb_version.is_some() {
        build.lldb_python_dir = run(Command::new("lldb").arg("-P")).ok();
    }
}
<commit_msg>[emscripten] Disable jemalloc for emscripten<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.

//! Sanity checking performed by rustbuild before actually executing anything.
//!
//! This module contains the implementation of ensuring that the build
//! environment looks reasonable before progressing. This will verify that
//! various programs like git and python exist, along with ensuring that all C
//! compilers for cross-compiling are found.
//!
//! In theory if we get past this phase it's a bug if a build fails, but in
//! practice that's likely not true!

use std::collections::HashSet;
use std::env;
use std::ffi::{OsStr, OsString};
use std::fs;
use std::process::Command;

use build_helper::output;

use Build;

pub fn check(build: &mut Build) {
    let mut checked = HashSet::new();
    let path = env::var_os("PATH").unwrap_or(OsString::new());
    // On Windows, quotes are invalid characters for filename paths, and if
    // one is present as part of the PATH then that can lead to the system
    // being unable to identify the files properly. See
    // https://github.com/rust-lang/rust/issues/34959 for more details.
    if cfg!(windows) {
        if path.to_string_lossy().contains("\"") {
            panic!("PATH contains invalid character '\"'");
        }
    }
    let mut need_cmd = |cmd: &OsStr| {
        if !checked.insert(cmd.to_owned()) {
            return
        }
        for path in env::split_paths(&path).map(|p| p.join(cmd)) {
            if fs::metadata(&path).is_ok() ||
               fs::metadata(path.with_extension("exe")).is_ok() {
                return
            }
        }
        panic!("\n\ncouldn't find required command: {:?}\n\n", cmd);
    };

    // If we've got a git directory we're gona need git to update
    // submodules and learn about various other aspects.
    if fs::metadata(build.src.join(".git")).is_ok() {
        need_cmd("git".as_ref());
    }

    // We need cmake, but only if we're actually building LLVM
    for host in build.config.host.iter() {
        if let Some(config) = build.config.target_config.get(host) {
            if config.llvm_config.is_some() {
                continue
            }
        }
        need_cmd("cmake".as_ref());
        if build.config.ninja {
            need_cmd("ninja".as_ref())
        }
        break
    }

    need_cmd("python".as_ref());

    // We're gonna build some custom C code here and there, host triples
    // also build some C++ shims for LLVM so we need a C++ compiler.
    for target in build.config.target.iter() {
        need_cmd(build.cc(target).as_ref());
        if let Some(ar) = build.ar(target) {
            need_cmd(ar.as_ref());
        }
    }
    for host in build.config.host.iter() {
        need_cmd(build.cxx(host).as_ref());
    }

    // Externally configured LLVM requires FileCheck to exist
    let filecheck = build.llvm_filecheck(&build.config.build);
    if !filecheck.starts_with(&build.out) && !filecheck.exists() {
        panic!("filecheck executable {:?} does not exist", filecheck);
    }

    for target in build.config.target.iter() {
        // Either can't build or don't want to run jemalloc on these targets
        if target.contains("rumprun") ||
           target.contains("bitrig") ||
           target.contains("openbsd") ||
           target.contains("msvc") ||
           target.contains("emscripten") {
            build.config.use_jemalloc = false;
        }

        // Can't compile for iOS unless we're on OSX
        if target.contains("apple-ios") &&
           !build.config.build.contains("apple-darwin") {
            panic!("the iOS target is only supported on OSX");
        }

        // Make sure musl-root is valid if specified
        if target.contains("musl") && !target.contains("mips") {
            match build.config.musl_root {
                Some(ref root) => {
                    if fs::metadata(root.join("lib/libc.a")).is_err() {
                        panic!("couldn't find libc.a in musl dir: {}",
                               root.join("lib").display());
                    }
                    if fs::metadata(root.join("lib/libunwind.a")).is_err() {
                        panic!("couldn't find libunwind.a in musl dir: {}",
                               root.join("lib").display());
                    }
                }
                None => {
                    panic!("when targeting MUSL the build.musl-root option \
                            must be specified in config.toml")
                }
            }
        }

        if target.contains("msvc") {
            // There are three builds of cmake on windows: MSVC, MinGW, and
            // Cygwin. The Cygwin build does not have generators for Visual
            // Studio, so detect that here and error.
            let out = output(Command::new("cmake").arg("--help"));
            if !out.contains("Visual Studio") {
                panic!("
cmake does not support Visual Studio generators.

This is likely due to it being an msys/cygwin build of cmake,
rather than the required windows version, built using MinGW
or Visual Studio.

If you are building under msys2 try installing the mingw-w64-x86_64-cmake
package instead of cmake:

$ pacman -R cmake && pacman -S mingw-w64-x86_64-cmake
");
            }
        }

        if target.contains("arm-linux-android") {
            need_cmd("adb".as_ref());
        }
    }

    for host in build.flags.host.iter() {
        if !build.config.host.contains(host) {
            panic!("specified host `{}` is not in the ./configure list", host);
        }
    }
    for target in build.flags.target.iter() {
        if !build.config.target.contains(target) {
            panic!("specified target `{}` is not in the ./configure list",
                   target);
        }
    }

    let run = |cmd: &mut Command| {
        cmd.output().map(|output| {
            String::from_utf8_lossy(&output.stdout)
                   .lines().next().unwrap()
                   .to_string()
        })
    };
    build.gdb_version = run(Command::new("gdb").arg("--version")).ok();
    build.lldb_version = run(Command::new("lldb").arg("--version")).ok();
    if build.lldb_version.is_some() {
        build.lldb_python_dir = run(Command::new("lldb").arg("-P")).ok();
    }
}
<|endoftext|>


<commit_before><commit_msg>lots of impl<commit_after><|endoftext|>


<commit_before><commit_msg>Add test of slice.eq to assert!/simple.rs<commit_after><|endoftext|>


<commit_before>// -*- rust -*-

use std;
import std.map;
import std.util;

fn test_simple() {
  log "*** starting test_simple";

  fn eq(&uint x, &uint y) -> bool { ret x == y; }
  fn hash(&uint u) -> uint {
    // FIXME: can't use std.util.id since we'd be capturing a type param,
    // and presently we can't close items over type params.
    ret u;
  }

  let map.hashfn[uint] hasher = hash;
  let map.eqfn[uint] eqer = eq;
  let map.hashmap[uint, uint] hm = map.mk_hashmap[uint, uint](hasher, eqer);

  check (hm.insert(10u, 12u));
  check (hm.insert(11u, 13u));
  check (hm.insert(12u, 14u));

  check (hm.get(11u) == 13u);
  check (hm.get(12u) == 14u);
  check (hm.get(10u) == 12u);

  check (!hm.insert(12u, 14u));
  check (hm.get(12u) == 14u);

  check (!hm.insert(12u, 12u));
  check (hm.get(12u) == 12u);

  log "*** finished test_simple";
}

/**
 * Force map growth and rehashing.
 */
fn test_growth() {
  log "*** starting test_growth";

  let uint num_to_insert = 64u;

  fn eq(&uint x, &uint y) -> bool { ret x == y; }
  fn hash(&uint u) -> uint {
    // FIXME: can't use std.util.id since we'd be capturing a type param,
    // and presently we can't close items over type params.
    ret u;
  }

  let map.hashfn[uint] hasher = hash;
  let map.eqfn[uint] eqer = eq;
  let map.hashmap[uint, uint] hm = map.mk_hashmap[uint, uint](hasher, eqer);

  let uint i = 0u;
  while (i < num_to_insert) {
    check (hm.insert(i, i * i));
    log "inserting " + std._uint.to_str(i, 10u)
      + " -> " + std._uint.to_str(i * i, 10u);
    i += 1u;
  }

  log "-----";

  i = 0u;
  while (i < num_to_insert) {
    log "get(" + std._uint.to_str(i, 10u) + ") = "
      + std._uint.to_str(hm.get(i), 10u);
    check (hm.get(i) == i * i);
    i += 1u;
  }

  check (hm.insert(num_to_insert, 17u));
  check (hm.get(num_to_insert) == 17u);

  log "-----";

  hm.rehash();

  i = 0u;
  while (i < num_to_insert) {
    log "get(" + std._uint.to_str(i, 10u) + ") = "
      + std._uint.to_str(hm.get(i), 10u);
    check (hm.get(i) == i * i);
    i += 1u;
  }

  log "*** finished test_growth";
}

fn test_removal() {
  log "*** starting test_removal";

  let uint num_to_insert = 64u;

  fn eq(&uint x, &uint y) -> bool { ret x == y; }
  fn hash(&uint u) -> uint {
    // This hash function intentionally causes collisions between
    // consecutive integer pairs.
    ret (u / 2u) * 2u;
  }

  check (hash(0u) == hash(1u));
  check (hash(2u) == hash(3u));
  check (hash(0u) != hash(2u));

  let map.hashfn[uint] hasher = hash;
  let map.eqfn[uint] eqer = eq;
  let map.hashmap[uint, uint] hm = map.mk_hashmap[uint, uint](hasher, eqer);

  let uint i = 0u;
  while (i < num_to_insert) {
    check (hm.insert(i, i * i));
    log "inserting " + std._uint.to_str(i, 10u)
      + " -> " + std._uint.to_str(i * i, 10u);
    i += 1u;
  }

  check (hm.size() == num_to_insert);

  log "-----";
  log "removing evens";

  i = 0u;
  while (i < num_to_insert) {
    /**
     * FIXME (issue #150): we want to check the removed value as in the
     * following:

    let util.option[uint] v = hm.remove(i);
    alt (v) {
      case (util.some[uint](u)) {
        check (u == (i * i));
      }
      case (util.none[uint]()) { fail; }
    }

     * but we util.option is a tag type so util.some and util.none are
     * off limits until we parse the dwarf for tag types.
     */

    hm.remove(i);
    i += 2u;
  }

  check (hm.size() == (num_to_insert / 2u));

  log "-----";

  i = 1u;
  while (i < num_to_insert) {
    log "get(" + std._uint.to_str(i, 10u) + ") = "
      + std._uint.to_str(hm.get(i), 10u);
    check (hm.get(i) == i * i);
    i += 2u;
  }

  log "-----";
  log "rehashing";

  hm.rehash();

  log "-----";

  i = 1u;
  while (i < num_to_insert) {
    log "get(" + std._uint.to_str(i, 10u) + ") = "
      + std._uint.to_str(hm.get(i), 10u);
    check (hm.get(i) == i * i);
    i += 2u;
  }

  log "-----";

  i = 0u;
  while (i < num_to_insert) {
    check (hm.insert(i, i * i));
    log "inserting " + std._uint.to_str(i, 10u)
      + " -> " + std._uint.to_str(i * i, 10u);
    i += 2u;
  }

  check (hm.size() == num_to_insert);

  log "-----";

  i = 0u;
  while (i < num_to_insert) {
    log "get(" + std._uint.to_str(i, 10u) + ") = "
      + std._uint.to_str(hm.get(i), 10u);
    check (hm.get(i) == i * i);
    i += 1u;
  }

  log "-----";
  log "rehashing";

  hm.rehash();

  log "-----";

  check (hm.size() == num_to_insert);

  i = 0u;
  while (i < num_to_insert) {
    log "get(" + std._uint.to_str(i, 10u) + ") = "
      + std._uint.to_str(hm.get(i), 10u);
    check (hm.get(i) == i * i);
    i += 1u;
  }

  log "*** finished test_removal";
}

fn main() {
  test_simple();
  test_growth();
  test_removal();
}
<commit_msg>Add simple hashmap tests exercising maps with str as key type, value type, and both.<commit_after>// -*- rust -*-

use std;
import std.map;
import std._str;
import std.util;

fn test_simple() {
  log "*** starting test_simple";

  fn eq_uint(&uint x, &uint y) -> bool { ret x == y; }
  fn hash_uint(&uint u) -> uint {
    // FIXME: can't use std.util.id since we'd be capturing a type param,
    // and presently we can't close items over type params.
    ret u;
  }

  let map.hashfn[uint] hasher_uint = hash_uint;
  let map.eqfn[uint] eqer_uint = eq_uint;

  let map.hashfn[str] hasher_str = _str.hash;
  let map.eqfn[str] eqer_str = _str.eq;

  log "uint -> uint";

  let map.hashmap[uint, uint] hm_uu = map.mk_hashmap[uint, uint](hasher_uint,
                                                                 eqer_uint);

  check (hm_uu.insert(10u, 12u));
  check (hm_uu.insert(11u, 13u));
  check (hm_uu.insert(12u, 14u));

  check (hm_uu.get(11u) == 13u);
  check (hm_uu.get(12u) == 14u);
  check (hm_uu.get(10u) == 12u);

  check (!hm_uu.insert(12u, 14u));
  check (hm_uu.get(12u) == 14u);

  check (!hm_uu.insert(12u, 12u));
  check (hm_uu.get(12u) == 12u);

  log "str -> uint";

  let map.hashmap[str, uint] hm_su = map.mk_hashmap[str, uint](hasher_str,
                                                               eqer_str);

  check (hm_su.insert("ten", 12u));
  check (hm_su.insert("eleven", 13u));
  check (hm_su.insert("twelve", 14u));

  check (hm_su.get("eleven") == 13u);
  check (hm_su.get("twelve") == 14u);
  check (hm_su.get("ten") == 12u);

  check (!hm_su.insert("twelve", 14u));
  check (hm_su.get("twelve") == 14u);

  check (!hm_su.insert("twelve", 12u));
  check (hm_su.get("twelve") == 12u);

  log "uint -> str";

  let map.hashmap[uint, str] hm_us = map.mk_hashmap[uint, str](hasher_uint,
                                                               eqer_uint);

  check (hm_us.insert(10u, "twelve"));
  check (hm_us.insert(11u, "thirteen"));
  check (hm_us.insert(12u, "fourteen"));

  check (_str.eq(hm_us.get(11u), "thirteen"));
  check (_str.eq(hm_us.get(12u), "fourteen"));
  check (_str.eq(hm_us.get(10u), "twelve"));

  check (!hm_us.insert(12u, "fourteen"));
  check (_str.eq(hm_us.get(12u), "fourteen"));

  check (!hm_us.insert(12u, "twelve"));
  check (_str.eq(hm_us.get(12u), "twelve"));

  log "str -> str";

  let map.hashmap[str, str] hm_ss = map.mk_hashmap[str, str](hasher_str,
                                                             eqer_str);

  check (hm_ss.insert("ten", "twelve"));
  check (hm_ss.insert("eleven", "thirteen"));
  check (hm_ss.insert("twelve", "fourteen"));

  check (_str.eq(hm_ss.get("eleven"), "thirteen"));
  check (_str.eq(hm_ss.get("twelve"), "fourteen"));
  check (_str.eq(hm_ss.get("ten"), "twelve"));

  check (!hm_ss.insert("twelve", "fourteen"));
  check (_str.eq(hm_ss.get("twelve"), "fourteen"));

  check (!hm_ss.insert("twelve", "twelve"));
  check (_str.eq(hm_ss.get("twelve"), "twelve"));

  log "*** finished test_simple";
}

/**
 * Force map growth and rehashing.
 */
fn test_growth() {
  log "*** starting test_growth";

  let uint num_to_insert = 64u;

  fn eq(&uint x, &uint y) -> bool { ret x == y; }
  fn hash(&uint u) -> uint {
    // FIXME: can't use std.util.id since we'd be capturing a type param,
    // and presently we can't close items over type params.
    ret u;
  }

  let map.hashfn[uint] hasher = hash;
  let map.eqfn[uint] eqer = eq;
  let map.hashmap[uint, uint] hm = map.mk_hashmap[uint, uint](hasher, eqer);

  let uint i = 0u;
  while (i < num_to_insert) {
    check (hm.insert(i, i * i));
    log "inserting " + std._uint.to_str(i, 10u)
      + " -> " + std._uint.to_str(i * i, 10u);
    i += 1u;
  }

  log "-----";

  i = 0u;
  while (i < num_to_insert) {
    log "get(" + std._uint.to_str(i, 10u) + ") = "
      + std._uint.to_str(hm.get(i), 10u);
    check (hm.get(i) == i * i);
    i += 1u;
  }

  check (hm.insert(num_to_insert, 17u));
  check (hm.get(num_to_insert) == 17u);

  log "-----";

  hm.rehash();

  i = 0u;
  while (i < num_to_insert) {
    log "get(" + std._uint.to_str(i, 10u) + ") = "
      + std._uint.to_str(hm.get(i), 10u);
    check (hm.get(i) == i * i);
    i += 1u;
  }

  log "*** finished test_growth";
}

fn test_removal() {
  log "*** starting test_removal";

  let uint num_to_insert = 64u;

  fn eq(&uint x, &uint y) -> bool { ret x == y; }
  fn hash(&uint u) -> uint {
    // This hash function intentionally causes collisions between
    // consecutive integer pairs.
    ret (u / 2u) * 2u;
  }

  check (hash(0u) == hash(1u));
  check (hash(2u) == hash(3u));
  check (hash(0u) != hash(2u));

  let map.hashfn[uint] hasher = hash;
  let map.eqfn[uint] eqer = eq;
  let map.hashmap[uint, uint] hm = map.mk_hashmap[uint, uint](hasher, eqer);

  let uint i = 0u;
  while (i < num_to_insert) {
    check (hm.insert(i, i * i));
    log "inserting " + std._uint.to_str(i, 10u)
      + " -> " + std._uint.to_str(i * i, 10u);
    i += 1u;
  }

  check (hm.size() == num_to_insert);

  log "-----";
  log "removing evens";

  i = 0u;
  while (i < num_to_insert) {
    /**
     * FIXME (issue #150): we want to check the removed value as in the
     * following:

    let util.option[uint] v = hm.remove(i);
    alt (v) {
      case (util.some[uint](u)) {
        check (u == (i * i));
      }
      case (util.none[uint]()) { fail; }
    }

     * but we util.option is a tag type so util.some and util.none are
     * off limits until we parse the dwarf for tag types.
     */

    hm.remove(i);
    i += 2u;
  }

  check (hm.size() == (num_to_insert / 2u));

  log "-----";

  i = 1u;
  while (i < num_to_insert) {
    log "get(" + std._uint.to_str(i, 10u) + ") = "
      + std._uint.to_str(hm.get(i), 10u);
    check (hm.get(i) == i * i);
    i += 2u;
  }

  log "-----";
  log "rehashing";

  hm.rehash();

  log "-----";

  i = 1u;
  while (i < num_to_insert) {
    log "get(" + std._uint.to_str(i, 10u) + ") = "
      + std._uint.to_str(hm.get(i), 10u);
    check (hm.get(i) == i * i);
    i += 2u;
  }

  log "-----";

  i = 0u;
  while (i < num_to_insert) {
    check (hm.insert(i, i * i));
    log "inserting " + std._uint.to_str(i, 10u)
      + " -> " + std._uint.to_str(i * i, 10u);
    i += 2u;
  }

  check (hm.size() == num_to_insert);

  log "-----";

  i = 0u;
  while (i < num_to_insert) {
    log "get(" + std._uint.to_str(i, 10u) + ") = "
      + std._uint.to_str(hm.get(i), 10u);
    check (hm.get(i) == i * i);
    i += 1u;
  }

  log "-----";
  log "rehashing";

  hm.rehash();

  log "-----";

  check (hm.size() == num_to_insert);

  i = 0u;
  while (i < num_to_insert) {
    log "get(" + std._uint.to_str(i, 10u) + ") = "
      + std._uint.to_str(hm.get(i), 10u);
    check (hm.get(i) == i * i);
    i += 1u;
  }

  log "*** finished test_removal";
}

fn main() {
  test_simple();
  test_growth();
  test_removal();
}
<|endoftext|>


<commit_before><commit_msg>ToString generics fix<commit_after><|endoftext|>


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

// See https://github.com/rust-lang/rust/issues/38942

#[repr(u64)]
pub enum NSEventType {
    NSEventTypePressure,
}

pub const A: u64 = NSEventType::NSEventTypePressure as u64;

fn banana() -> u64 {
    A
}

fn main() {
    println!("banana! {}", banana());
}
<|endoftext|>


<commit_before><commit_msg>add regression test for #39984<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.

// Regression test for issue #39984.
//
// The key here is that the error type of the `Ok` call ought to be
// constrained to `String`, even though it is dead-code.

fn main() {}

fn t() -> Result<(), String> {
    return Err("".into());
    Ok(())
}
<|endoftext|>


<commit_before><commit_msg>StrippedStateContent: Add sender field<commit_after><|endoftext|>


<commit_before><commit_msg>Removed unnecessary references<commit_after><|endoftext|>


<commit_before><commit_msg>move lychrel finding loop out into a function<commit_after><|endoftext|>


<commit_before><commit_msg>Added main<commit_after>#![crate_id = "risp"]
#![crate_type = "bin"]

//! A Lisp interpreter.

extern crate libc;

use libc::c_char;
use std::c_str::Cstring;

#[link(name = "readline")]
extern {
    fn readline(p: *c_char) -> *c_char;
    fn add_history(l: *c_char);
}

/// Attempts to read input from a user using readline. Returns an option,
/// Some(StrBuf) for success, or None if EOF (^D) is entered.
pub fn rust_readline(prompt: &str) -> Option<StrBuf>
{
    if prompt.len() == 0 {
        return None
    }

    let c_prompt = prompt.to_c_str();

    c_prompt.with_ref(|c_buf| {
        unsafe {
            let ret_str = CString::new(readline(c_buf), true);
            if ret_str.is_not_null() {
                ret_str.as_str().map(|ret_str| ret_str.to_strbuf())
            } else {
                None
            }
        }
    })
}

/// Adds a string to a readline history.
pub fn rust_add_history(line: &str) {
    if line.len() == 0 {
        return
    }

    let c_line = line.to_c_str();
    c_line.with_ref(|c_line| {
        unsafe {
            add_history(c_line);
        }
    });
}

fn main()
{
    loop {
        let expr = match rust_readline(">>> ") {
            Some(val)   => { val.to_str() },
            None    => { continue }
        };
        rust_add_histor(expr);

        match expr.trim() {
            "(exit)" | "exit" | ",q"    => { break },
            _   => { println!("{}", expr); }
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Formatting.<commit_after><|endoftext|>


<commit_before><commit_msg>Remove presence<commit_after><|endoftext|>


<commit_before><commit_msg>The suer_mode.rs file is kind of impertant<commit_after>use vga;
use machine::{to_user_mode, get_esp, syscall};
use paging::give_to_user;

use core::fmt::{Write,Error};
use core::result::Result;

pub struct UserConsole;

impl Write for UserConsole {
    fn write_str(&mut self, data: &str) -> Result<(), Error> {
        let ptr = data.as_ptr();
        let len = data.len();
        let ret = syscall(1, ptr as u32, len as u32);
        if ret == 0 { Result::Ok(()) } else { Result::Err(Error) }
    }
}

pub extern fn user_main() {
    vga::write_string(0, 0, "User mode");
    match UserConsole.write_str("\r\nSyscall test\r\n") {
        Result::Ok(_) => vga::write_string(0, 30, "Post-interrupt"),
        _ => ()
    }
    loop {}
}

pub fn init() -> ! {
    give_to_user(get_esp() as usize);
    for page in 0x8..0xe0 {
        give_to_user(page << 12);
    }
    to_user_mode(user_main)
}
<|endoftext|>


<commit_before><commit_msg>Added Free Bank<commit_after><|endoftext|>


<commit_before><commit_msg>Lots of cleanup and Rust-ification<commit_after><|endoftext|>


<commit_before><commit_msg>Add implementation for validators<commit_after>//! Functions to be used for clap::Arg::validator()
//! to validate arguments

use std::path::PathBuf;
use boolinator::Boolinator;

pub fn is_file(s: String) -> Result<(), String> {
    PathBuf::from(s.clone()).is_file().as_result((), format!("Not a File: {}", s))
}

pub fn is_directory(s: String) -> Result<(), String> {
    PathBuf::from(s.clone()).is_dir().as_result((), format!("Not a Directory: {}", s))
}

pub fn is_integer(s: String) -> Result<(), String> {
    use std::str::FromStr;

    let i : Result<i64, _> = FromStr::from_str(&s);
    i.map(|_| ()).map_err(|_| format!("Not an integer: {}", s))
}

pub fn is_url(s: String) -> Result<(), String> {
    use url::Url;
    Url::parse(&s).map(|_| ()).map_err(|_| format!("Not a URL: {}", s))
}

<|endoftext|>


<commit_before><commit_msg>start hotkeys reminders<commit_after><|endoftext|>


<commit_before><commit_msg>Add tests<commit_after>extern crate racer_testutils;
use racer_testutils::*;

#[test]
fn completes_fields_for_binary_operators() {
    let src = r"
    use std::ops::Add;
    struct Left {
        x: i32,
        y: i32,
    }
    impl Add for Left {
        type Output = Left;
        fn add(self, other: Left) -> Self::Output {
            Left {
                x: self.x + other.x,
                y: self.y + other.y,
            }
        }
    }
    fn main() {
        let a = Left { x: 1, y: 0 } + Left { x: 2, y: 3 };
        a.~
    }
";
    let got = get_all_completions(src, None);
    assert!(got.iter().any(|ma| ma.matchstr == "x"));
    assert!(got.iter().any(|ma| ma.matchstr == "y"));
    assert!(got.iter().any(|ma| ma.matchstr == "add"));
}

#[test]
fn completes_binary_operators_for_different_types() {
    let src = r"
    use std::ops::Sub;
    struct Left {
        x: i32,
        y: i32,
    }
    struct Right {
        x: i32,
        y: i32
    }
    impl Sub<Right> for Left {
        type Output = Left;
        fn sub(self, other: Right) -> Self::Output {
            Left {
                x: self.x - other.x,
                y: self.y - other.y,
            }
        }
    }
    fn main() {
        let a = Left { x: 1, y: 0 } - Right { x: 2, y: 3 };
        a.~
    }
";
    let got = get_all_completions(src, None);
    assert!(got.iter().any(|ma| ma.matchstr == "x"));
    assert!(got.iter().any(|ma| ma.matchstr == "y"));
    assert!(got.iter().any(|ma| ma.matchstr == "sub"));
}

#[test]
fn test_operator_precedence_given_to_type_on_left() {
    let src = r"
    use std::ops::Sub;
    struct Left {
        x: i32,
        y: i32,
    }
    struct Right {
        x: i32,
        y: i32
    }
    struct Foo;
    impl Foo {
        fn foo(&self) -> Option<i32>  {
            Some(33)
        }
    }
    struct Bar;
    impl Bar {
        fn bar(&self) -> Option<i32>  {
            Some(33)
        }
    }
    impl Sub<Right> for Left {
        type Output = Foo;
        fn sub(self, other: Right) -> Self::Output {
             Foo
        }
    }
    impl Sub<Left> for Right {
        type Output = Bar;
        fn sub(self, other: Right) -> Self::Output {
             Bar
        }
    }
    fn main() {
        let a = Left { x: 1, y: 0 } - Right { x: 2, y: 3 };
        a.~
    }
";
    let got = get_one_completion(src, None);
    assert_eq!(got.matchstr, "foo".to_string());
}

#[test]
fn completes_if_operator_trait_is_not_explicit() {
    let src = r"
    use std::ops::Sub;
    struct Left {
        x: i32,
        y: i32,
    }
    struct Bar;
    impl Bar {
        fn bar(&self) -> Option<i32>  {
            Some(33)
        }
    }
    impl Sub for Left {
        type Output = Bar;
        fn sub(self, other: Left) -> Self::Output {
             Bar
        }
    }
    fn main() {
        let a = Left { x: 1, y: 0 } - Left { x: 2, y: 3 };
        a.~
    }
";
    let got = get_one_completion(src, None);
    assert_eq!(got.matchstr, "bar".to_string());
}
<|endoftext|>


<commit_before><commit_msg>Add test for comparing md5 checksums<commit_after>extern crate flac;
extern crate crypto;

use crypto::digest::Digest;
use crypto::md5::Md5;
use flac::Stream;
use std::cmp;

fn to_bytes(value: i32, buffer: &mut [u8]) {
  buffer[0] = value as u8;
  buffer[1] = (value >> 8) as u8;
  buffer[2] = (value >> 16) as u8;
  buffer[3] = (value >> 24) as u8;
}

fn get_offset(sample_size: usize) -> usize {
  let bits_per_sample = cmp::max(sample_size, 8);

  bits_per_sample / 8
}

#[test]
fn test_decoded_md5_sum() {
  let filename = "tests/assets/input-pictures.flac";

  let mut stream  = Stream::from_file(filename).unwrap();
  let mut buffer  = [0; 4];
  let mut md5     = Md5::new();
  let mut md5_sum = [0; 16];

  let info   = stream.info();
  let offset = get_offset(info.bits_per_sample as usize);

  for sample in stream.iter() {
    to_bytes(sample, &mut buffer);

    md5.input(&buffer[0..offset]);
  }

  md5.result(&mut md5_sum);

  assert_eq!(md5_sum, info.md5_sum);
}
<|endoftext|>


<commit_before>import io::reader_util;
import util::interner;
import lexer::{ reader, new_reader, next_token, is_whitespace };

export cmnt;
export lit;
export cmnt_style;
export gather_comments_and_literals;

enum cmnt_style {
    isolated, // No code on either side of each line of the comment
    trailing, // Code exists to the left of the comment
    mixed, // Code before /* foo */ and after the comment
    blank_line, // Just a manual blank line "\n\n", for layout
}

type cmnt = {style: cmnt_style, lines: [str], pos: uint};

fn read_to_eol(rdr: reader) -> str {
    let mut val = "";
    while rdr.curr != '\n' && !rdr.is_eof() {
        str::push_char(val, rdr.curr);
        rdr.bump();
    }
    if rdr.curr == '\n' { rdr.bump(); }
    ret val;
}

fn read_one_line_comment(rdr: reader) -> str {
    let val = read_to_eol(rdr);
    assert (val[0] == '/' as u8 && val[1] == '/' as u8);
    ret val;
}

fn consume_non_eol_whitespace(rdr: reader) {
    while is_whitespace(rdr.curr) && rdr.curr != '\n' && !rdr.is_eof() {
        rdr.bump();
    }
}

fn push_blank_line_comment(rdr: reader, &comments: [cmnt]) {
    #debug(">>> blank-line comment");
    let v: [str] = [];
    comments += [{style: blank_line, lines: v, pos: rdr.chpos}];
}

fn consume_whitespace_counting_blank_lines(rdr: reader, &comments: [cmnt]) {
    while is_whitespace(rdr.curr) && !rdr.is_eof() {
        if rdr.col == 0u && rdr.curr == '\n' {
            push_blank_line_comment(rdr, comments);
        }
        rdr.bump();
    }
}

fn read_line_comments(rdr: reader, code_to_the_left: bool) -> cmnt {
    #debug(">>> line comments");
    let p = rdr.chpos;
    let mut lines: [str] = [];
    while rdr.curr == '/' && rdr.next() == '/' {
        let line = read_one_line_comment(rdr);
        log(debug, line);
        lines += [line];
        consume_non_eol_whitespace(rdr);
    }
    #debug("<<< line comments");
    ret {style: if code_to_the_left { trailing } else { isolated },
         lines: lines,
         pos: p};
}

fn all_whitespace(s: str, begin: uint, end: uint) -> bool {
    let mut i: uint = begin;
    while i != end { if !is_whitespace(s[i] as char) { ret false; } i += 1u; }
    ret true;
}

fn trim_whitespace_prefix_and_push_line(&lines: [str],
                                        s: str, col: uint) unsafe {
    let mut s1;
    let len = str::len(s);
    if all_whitespace(s, 0u, uint::min(len, col)) {
        if col < len {
            s1 = str::slice(s, col, len);
        } else { s1 = ""; }
    } else { s1 = s; }
    log(debug, "pushing line: " + s1);
    lines += [s1];
}

fn read_block_comment(rdr: reader, code_to_the_left: bool) -> cmnt {
    #debug(">>> block comment");
    let p = rdr.chpos;
    let mut lines: [str] = [];
    let mut col: uint = rdr.col;
    rdr.bump();
    rdr.bump();
    let mut curr_line = "/*";
    let mut level: int = 1;
    while level > 0 {
        #debug("=== block comment level %d", level);
        if rdr.is_eof() { rdr.fatal("unterminated block comment"); }
        if rdr.curr == '\n' {
            trim_whitespace_prefix_and_push_line(lines, curr_line, col);
            curr_line = "";
            rdr.bump();
        } else {
            str::push_char(curr_line, rdr.curr);
            if rdr.curr == '/' && rdr.next() == '*' {
                rdr.bump();
                rdr.bump();
                curr_line += "*";
                level += 1;
            } else {
                if rdr.curr == '*' && rdr.next() == '/' {
                    rdr.bump();
                    rdr.bump();
                    curr_line += "/";
                    level -= 1;
                } else { rdr.bump(); }
            }
        }
    }
    if str::len(curr_line) != 0u {
        trim_whitespace_prefix_and_push_line(lines, curr_line, col);
    }
    let mut style = if code_to_the_left { trailing } else { isolated };
    consume_non_eol_whitespace(rdr);
    if !rdr.is_eof() && rdr.curr != '\n' && vec::len(lines) == 1u {
        style = mixed;
    }
    #debug("<<< block comment");
    ret {style: style, lines: lines, pos: p};
}

fn peeking_at_comment(rdr: reader) -> bool {
    ret rdr.curr == '/' && rdr.next() == '/' ||
            rdr.curr == '/' && rdr.next() == '*';
}

fn consume_comment(rdr: reader, code_to_the_left: bool, &comments: [cmnt]) {
    #debug(">>> consume comment");
    if rdr.curr == '/' && rdr.next() == '/' {
        comments += [read_line_comments(rdr, code_to_the_left)];
    } else if rdr.curr == '/' && rdr.next() == '*' {
        comments += [read_block_comment(rdr, code_to_the_left)];
    } else { fail; }
    #debug("<<< consume comment");
}

type lit = {lit: str, pos: uint};

fn gather_comments_and_literals(span_diagnostic: diagnostic::span_handler,
                                path: str,
                                srdr: io::reader) ->
   {cmnts: [cmnt], lits: [lit]} {
    let src = @str::from_bytes(srdr.read_whole_stream());
    let itr = @interner::mk::<str>(str::hash, str::eq);
    let rdr = new_reader(span_diagnostic,
                         codemap::new_filemap(path, src, 0u, 0u), itr);
    let mut comments: [cmnt] = [];
    let mut literals: [lit] = [];
    let mut first_read: bool = true;
    while !rdr.is_eof() {
        loop {
            let mut code_to_the_left = !first_read;
            consume_non_eol_whitespace(rdr);
            if rdr.curr == '\n' {
                code_to_the_left = false;
                consume_whitespace_counting_blank_lines(rdr, comments);
            }
            while peeking_at_comment(rdr) {
                consume_comment(rdr, code_to_the_left, comments);
                consume_whitespace_counting_blank_lines(rdr, comments);
            }
            break;
        }
        let tok = next_token(rdr);
        if token::is_lit(tok.tok) {
            let s = rdr.get_str_from(tok.bpos);
            literals += [{lit: s, pos: tok.chpos}];
            log(debug, "tok lit: " + s);
        } else {
            log(debug, "tok: " + token::to_str(*rdr.interner, tok.tok));
        }
        first_read = false;
    }
    ret {cmnts: comments, lits: literals};
}
<commit_msg>Changed the pretty printer also read #! comments<commit_after>import io::reader_util;
import io::println;//XXXXXXXXxxx
import util::interner;
import lexer::{ reader, new_reader, next_token, is_whitespace };

export cmnt;
export lit;
export cmnt_style;
export gather_comments_and_literals;

enum cmnt_style {
    isolated, // No code on either side of each line of the comment
    trailing, // Code exists to the left of the comment
    mixed, // Code before /* foo */ and after the comment
    blank_line, // Just a manual blank line "\n\n", for layout
}

type cmnt = {style: cmnt_style, lines: [str], pos: uint};

fn read_to_eol(rdr: reader) -> str {
    let mut val = "";
    while rdr.curr != '\n' && !rdr.is_eof() {
        str::push_char(val, rdr.curr);
        rdr.bump();
    }
    if rdr.curr == '\n' { rdr.bump(); }
    ret val;
}

fn read_one_line_comment(rdr: reader) -> str {
    let val = read_to_eol(rdr);
    assert ((val[0] == '/' as u8 && val[1] == '/' as u8) ||
            (val[0] == '#' as u8 && val[1] == '!' as u8));
    ret val;
}

fn consume_non_eol_whitespace(rdr: reader) {
    while is_whitespace(rdr.curr) && rdr.curr != '\n' && !rdr.is_eof() {
        rdr.bump();
    }
}

fn push_blank_line_comment(rdr: reader, &comments: [cmnt]) {
    #debug(">>> blank-line comment");
    let v: [str] = [];
    comments += [{style: blank_line, lines: v, pos: rdr.chpos}];
}

fn consume_whitespace_counting_blank_lines(rdr: reader, &comments: [cmnt]) {
    while is_whitespace(rdr.curr) && !rdr.is_eof() {
        if rdr.col == 0u && rdr.curr == '\n' {
            push_blank_line_comment(rdr, comments);
        }
        rdr.bump();
    }
}

fn read_shebang_comment(rdr: reader, code_to_the_left: bool) -> cmnt {
    #debug(">>> shebang comment");
    let p = rdr.chpos;
    #debug("<<< shebang comment");
    ret {style: if code_to_the_left { trailing } else { isolated },
         lines: [read_one_line_comment(rdr)],
         pos: p};
}

fn read_line_comments(rdr: reader, code_to_the_left: bool) -> cmnt {
    #debug(">>> line comments");
    let p = rdr.chpos;
    let mut lines: [str] = [];
    while rdr.curr == '/' && rdr.next() == '/' {
        let line = read_one_line_comment(rdr);
        log(debug, line);
        lines += [line];
        consume_non_eol_whitespace(rdr);
    }
    #debug("<<< line comments");
    ret {style: if code_to_the_left { trailing } else { isolated },
         lines: lines,
         pos: p};
}

fn all_whitespace(s: str, begin: uint, end: uint) -> bool {
    let mut i: uint = begin;
    while i != end { if !is_whitespace(s[i] as char) { ret false; } i += 1u; }
    ret true;
}

fn trim_whitespace_prefix_and_push_line(&lines: [str],
                                        s: str, col: uint) unsafe {
    let mut s1;
    let len = str::len(s);
    if all_whitespace(s, 0u, uint::min(len, col)) {
        if col < len {
            s1 = str::slice(s, col, len);
        } else { s1 = ""; }
    } else { s1 = s; }
    log(debug, "pushing line: " + s1);
    lines += [s1];
}

fn read_block_comment(rdr: reader, code_to_the_left: bool) -> cmnt {
    #debug(">>> block comment");
    let p = rdr.chpos;
    let mut lines: [str] = [];
    let mut col: uint = rdr.col;
    rdr.bump();
    rdr.bump();
    let mut curr_line = "/*";
    let mut level: int = 1;
    while level > 0 {
        #debug("=== block comment level %d", level);
        if rdr.is_eof() { rdr.fatal("unterminated block comment"); }
        if rdr.curr == '\n' {
            trim_whitespace_prefix_and_push_line(lines, curr_line, col);
            curr_line = "";
            rdr.bump();
        } else {
            str::push_char(curr_line, rdr.curr);
            if rdr.curr == '/' && rdr.next() == '*' {
                rdr.bump();
                rdr.bump();
                curr_line += "*";
                level += 1;
            } else {
                if rdr.curr == '*' && rdr.next() == '/' {
                    rdr.bump();
                    rdr.bump();
                    curr_line += "/";
                    level -= 1;
                } else { rdr.bump(); }
            }
        }
    }
    if str::len(curr_line) != 0u {
        trim_whitespace_prefix_and_push_line(lines, curr_line, col);
    }
    let mut style = if code_to_the_left { trailing } else { isolated };
    consume_non_eol_whitespace(rdr);
    if !rdr.is_eof() && rdr.curr != '\n' && vec::len(lines) == 1u {
        style = mixed;
    }
    #debug("<<< block comment");
    ret {style: style, lines: lines, pos: p};
}

fn peeking_at_comment(rdr: reader) -> bool {
    ret ((rdr.curr == '/' && rdr.next() == '/') ||
         (rdr.curr == '/' && rdr.next() == '*')) ||
        (rdr.curr == '#' && rdr.next() == '!');
}

fn consume_comment(rdr: reader, code_to_the_left: bool, &comments: [cmnt]) {
    #debug(">>> consume comment");
    if rdr.curr == '/' && rdr.next() == '/' {
        comments += [read_line_comments(rdr, code_to_the_left)];
    } else if rdr.curr == '/' && rdr.next() == '*' {
        comments += [read_block_comment(rdr, code_to_the_left)];
    } else if rdr.curr == '#' && rdr.next() == '!' {
        comments += [read_shebang_comment(rdr, code_to_the_left)];
    } else { fail; }
    #debug("<<< consume comment");
}

type lit = {lit: str, pos: uint};

fn gather_comments_and_literals(span_diagnostic: diagnostic::span_handler,
                                path: str,
                                srdr: io::reader) ->
   {cmnts: [cmnt], lits: [lit]} {
    let src = @str::from_bytes(srdr.read_whole_stream());
    let itr = @interner::mk::<str>(str::hash, str::eq);
    let rdr = new_reader(span_diagnostic,
                         codemap::new_filemap(path, src, 0u, 0u), itr);
    let mut comments: [cmnt] = [];
    let mut literals: [lit] = [];
    let mut first_read: bool = true;
    while !rdr.is_eof() {
        loop {
            let mut code_to_the_left = !first_read;
            consume_non_eol_whitespace(rdr);
            if rdr.curr == '\n' {
                code_to_the_left = false;
                consume_whitespace_counting_blank_lines(rdr, comments);
            }
            while peeking_at_comment(rdr) {
                consume_comment(rdr, code_to_the_left, comments);
                consume_whitespace_counting_blank_lines(rdr, comments);
            }
            break;
        }
        let tok = next_token(rdr);
        if token::is_lit(tok.tok) {
            let s = rdr.get_str_from(tok.bpos);
            literals += [{lit: s, pos: tok.chpos}];
            log(debug, "tok lit: " + s);
        } else {
            log(debug, "tok: " + token::to_str(*rdr.interner, tok.tok));
        }
        first_read = false;
    }
    ret {cmnts: comments, lits: literals};
}
<|endoftext|>


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

use std::cell::RefCell;
use std::collections::BTreeMap;

use ast;
use ast::{Ident, Name, TokenTree};
use codemap::Span;
use ext::base::{ExtCtxt, MacEager, MacResult};
use ext::build::AstBuilder;
use parse::token;
use ptr::P;
use util::small_vector::SmallVector;

thread_local! {
    static REGISTERED_DIAGNOSTICS: RefCell<BTreeMap<Name, Option<Name>>> = {
        RefCell::new(BTreeMap::new())
    }
}
thread_local! {
    static USED_DIAGNOSTICS: RefCell<BTreeMap<Name, Span>> = {
        RefCell::new(BTreeMap::new())
    }
}

fn with_registered_diagnostics<T, F>(f: F) -> T where
    F: FnOnce(&mut BTreeMap<Name, Option<Name>>) -> T,
{
    REGISTERED_DIAGNOSTICS.with(move |slot| {
        f(&mut *slot.borrow_mut())
    })
}

fn with_used_diagnostics<T, F>(f: F) -> T where
    F: FnOnce(&mut BTreeMap<Name, Span>) -> T,
{
    USED_DIAGNOSTICS.with(move |slot| {
        f(&mut *slot.borrow_mut())
    })
}

pub fn expand_diagnostic_used<'cx>(ecx: &'cx mut ExtCtxt,
                                   span: Span,
                                   token_tree: &[TokenTree])
                                   -> Box<MacResult+'cx> {
    let code = match token_tree {
        [ast::TtToken(_, token::Ident(code, _))] => code,
        _ => unreachable!()
    };
    with_used_diagnostics(|diagnostics| {
        match diagnostics.insert(code.name, span) {
            Some(previous_span) => {
                ecx.span_warn(span, &format!(
                    "diagnostic code {} already used", &token::get_ident(code)
                ));
                ecx.span_note(previous_span, "previous invocation");
            },
            None => ()
        }
        ()
    });
    with_registered_diagnostics(|diagnostics| {
        if !diagnostics.contains_key(&code.name) {
            ecx.span_err(span, &format!(
                "used diagnostic code {} not registered", &token::get_ident(code)
            ));
        }
    });
    MacEager::expr(quote_expr!(ecx, ()))
}

pub fn expand_register_diagnostic<'cx>(ecx: &'cx mut ExtCtxt,
                                       span: Span,
                                       token_tree: &[TokenTree])
                                       -> Box<MacResult+'cx> {
    let (code, description) = match token_tree {
        [ast::TtToken(_, token::Ident(ref code, _))] => {
            (code, None)
        },
        [ast::TtToken(_, token::Ident(ref code, _)),
         ast::TtToken(_, token::Comma),
         ast::TtToken(_, token::Literal(token::StrRaw(description, _), None))] => {
            (code, Some(description))
        }
        _ => unreachable!()
    };
    with_registered_diagnostics(|diagnostics| {
        if diagnostics.insert(code.name, description).is_some() {
            ecx.span_err(span, &format!(
                "diagnostic code {} already registered", &token::get_ident(*code)
            ));
        }
    });
    let sym = Ident::new(token::gensym(&(
        "__register_diagnostic_".to_string() + &token::get_ident(*code)
    )));
    MacEager::items(SmallVector::many(vec![quote_item!(ecx, mod $sym {}).unwrap()]))
}

pub fn expand_build_diagnostic_array<'cx>(ecx: &'cx mut ExtCtxt,
                                          span: Span,
                                          token_tree: &[TokenTree])
                                          -> Box<MacResult+'cx> {
    let name = match token_tree {
        [ast::TtToken(_, token::Ident(ref name, _))] => name,
        _ => unreachable!()
    };

    let (count, expr) =
        with_registered_diagnostics(|diagnostics| {
            let descriptions: Vec<P<ast::Expr>> =
                diagnostics.iter().filter_map(|(code, description)| {
                    description.map(|description| {
                        ecx.expr_tuple(span, vec![
                            ecx.expr_str(span, token::get_name(*code)),
                            ecx.expr_str(span, token::get_name(description))])
                    })
                }).collect();
            (descriptions.len(), ecx.expr_vec(span, descriptions))
        });

    MacEager::items(SmallVector::many(vec![quote_item!(ecx,
        pub static $name: [(&'static str, &'static str); $count] = $expr;
    ).unwrap()]))
}
<commit_msg>Validate format of extended error descriptions.<commit_after>// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use std::cell::RefCell;
use std::collections::BTreeMap;

use ast;
use ast::{Ident, Name, TokenTree};
use codemap::Span;
use ext::base::{ExtCtxt, MacEager, MacResult};
use ext::build::AstBuilder;
use parse::token;
use ptr::P;
use util::small_vector::SmallVector;

thread_local! {
    static REGISTERED_DIAGNOSTICS: RefCell<BTreeMap<Name, Option<Name>>> = {
        RefCell::new(BTreeMap::new())
    }
}
thread_local! {
    static USED_DIAGNOSTICS: RefCell<BTreeMap<Name, Span>> = {
        RefCell::new(BTreeMap::new())
    }
}

fn with_registered_diagnostics<T, F>(f: F) -> T where
    F: FnOnce(&mut BTreeMap<Name, Option<Name>>) -> T,
{
    REGISTERED_DIAGNOSTICS.with(move |slot| {
        f(&mut *slot.borrow_mut())
    })
}

fn with_used_diagnostics<T, F>(f: F) -> T where
    F: FnOnce(&mut BTreeMap<Name, Span>) -> T,
{
    USED_DIAGNOSTICS.with(move |slot| {
        f(&mut *slot.borrow_mut())
    })
}

pub fn expand_diagnostic_used<'cx>(ecx: &'cx mut ExtCtxt,
                                   span: Span,
                                   token_tree: &[TokenTree])
                                   -> Box<MacResult+'cx> {
    let code = match token_tree {
        [ast::TtToken(_, token::Ident(code, _))] => code,
        _ => unreachable!()
    };
    with_used_diagnostics(|diagnostics| {
        match diagnostics.insert(code.name, span) {
            Some(previous_span) => {
                ecx.span_warn(span, &format!(
                    "diagnostic code {} already used", &token::get_ident(code)
                ));
                ecx.span_note(previous_span, "previous invocation");
            },
            None => ()
        }
        ()
    });
    with_registered_diagnostics(|diagnostics| {
        if !diagnostics.contains_key(&code.name) {
            ecx.span_err(span, &format!(
                "used diagnostic code {} not registered", &token::get_ident(code)
            ));
        }
    });
    MacEager::expr(quote_expr!(ecx, ()))
}

pub fn expand_register_diagnostic<'cx>(ecx: &'cx mut ExtCtxt,
                                       span: Span,
                                       token_tree: &[TokenTree])
                                       -> Box<MacResult+'cx> {
    let (code, description) = match token_tree {
        [ast::TtToken(_, token::Ident(ref code, _))] => {
            (code, None)
        },
        [ast::TtToken(_, token::Ident(ref code, _)),
         ast::TtToken(_, token::Comma),
         ast::TtToken(_, token::Literal(token::StrRaw(description, _), None))] => {
            (code, Some(description))
        }
        _ => unreachable!()
    };
    // Check that the description starts and ends with a newline.
    description.map(|raw_msg| {
        let msg = raw_msg.as_str();
        let last = msg.len() - 1;
        if &msg[0..1] != "\n" || &msg[last..] != "\n" {
            ecx.span_err(span, &format!(
                "description for error code {} doesn't start and end with a newline",
                token::get_ident(*code)
            ));
        }
        raw_msg
    });
    with_registered_diagnostics(|diagnostics| {
        if diagnostics.insert(code.name, description).is_some() {
            ecx.span_err(span, &format!(
                "diagnostic code {} already registered", &token::get_ident(*code)
            ));
        }
    });
    let sym = Ident::new(token::gensym(&(
        "__register_diagnostic_".to_string() + &token::get_ident(*code)
    )));
    MacEager::items(SmallVector::many(vec![quote_item!(ecx, mod $sym {}).unwrap()]))
}

pub fn expand_build_diagnostic_array<'cx>(ecx: &'cx mut ExtCtxt,
                                          span: Span,
                                          token_tree: &[TokenTree])
                                          -> Box<MacResult+'cx> {
    let name = match token_tree {
        [ast::TtToken(_, token::Ident(ref name, _))] => name,
        _ => unreachable!()
    };

    let (count, expr) =
        with_registered_diagnostics(|diagnostics| {
            let descriptions: Vec<P<ast::Expr>> =
                diagnostics.iter().filter_map(|(code, description)| {
                    description.map(|description| {
                        ecx.expr_tuple(span, vec![
                            ecx.expr_str(span, token::get_name(*code)),
                            ecx.expr_str(span, token::get_name(description))])
                    })
                }).collect();
            (descriptions.len(), ecx.expr_vec(span, descriptions))
        });

    MacEager::items(SmallVector::many(vec![quote_item!(ecx,
        pub static $name: [(&'static str, &'static str); $count] = $expr;
    ).unwrap()]))
}
<|endoftext|>


<commit_before><commit_msg>Add minimal reproducer for ICE in #6179<commit_after>//! This is a minimal reproducer for the ICE in https://github.com/rust-lang/rust-clippy/pull/6179.
//! The ICE is mainly caused by using `hir_ty_to_ty`. See the discussion in the PR for details.

#![warn(clippy::use_self)]
#![allow(dead_code)]

struct Foo {}

impl Foo {
    fn foo() -> Self {
        impl Foo {
            fn bar() {}
        }

        let _: _ = 1;

        Self {}
    }
}

fn main() {}
<|endoftext|>


<commit_before><commit_msg>Rust solution for problem 3<commit_after>/// Largest Prime Factor
///
/// The prime factors of 13195 are 5, 7, 13 and 29.
///
/// What is the largest prime factor of the number 600851475143 ?

use std::collections::HashMap;

fn find_next_prime(primes: &Vec<u64>) -> u64 {
    let last = primes[primes.len() - 1];
    let mut candidates = HashMap::new();

    let start: u64 = last + 1;
    let end: u64 = last * 2 + 1;

    for p in start..end {
        candidates.insert(p, 1);
    }

    for p in primes.iter() {
        let mut i = *p * 2;
        while i < end {
            candidates.insert(i, 0);
            i += *p;
        }
    }

    for i in start..end {
        let value = candidates[&i];
        if value == 1 {
            return i;
        }
    }

    return 0;
}

//fn int_vec_to_string(v: &Vec<u64>) -> String {
//    let d: Vec<String> = v.iter().map(|&x| x.to_string()).collect();
//    return d.connect(", ");
//}

fn find_largest_prime_factor(number: u64) -> u64 {
    let mut largest = 1;
    let mut primes = vec![2];
    let mut num = number;

    loop {
        let last = primes[primes.len() - 1];
        if num % last == 0 {
            largest = last;
            println!("{}", largest);
            num /= last;
        }

        // Keep dividing
        while num % last == 0 {
            num /= last
        }

        if num == 1 {
            return largest;
        }

        let next_prime = find_next_prime(&primes);
        primes.push(next_prime);
    }
}

fn main() {
    let number = 600851475143;
    let largest = find_largest_prime_factor(number);
    println!("Largest prime factor of {} is {}", number, largest);
    assert_eq!(6857, larget);
}

//#[test]
//fn test_find_next_prime() {
//    let mut primes = vec![2];
//    let mut p = find_next_prime(&primes);
//    assert_eq!(3, p);
//
//
//    primes = vec![2, 3];
//    p = find_next_prime(&primes);
//    assert_eq!(5, p);
//
//    primes = vec![2, 3, 5, 7];
//    p = find_next_prime(&primes);
//    assert_eq!(11, p);
//}
<|endoftext|>


<commit_before>use std::collections::{BTreeSet, HashMap, HashSet};
use std::env;
use std::ffi::OsStr;
use std::path::PathBuf;

use semver::Version;

use core::{Edition, Package, PackageId, Target, TargetKind};
use util::{self, join_paths, process, CargoResult, CfgExpr, Config, ProcessBuilder};
use super::BuildContext;

pub struct Doctest {
    /// The package being doctested.
    pub package: Package,
    /// The target being tested (currently always the package's lib).
    pub target: Target,
    /// Extern dependencies needed by `rustdoc`. The path is the location of
    /// the compiled lib.
    pub deps: Vec<(String, PathBuf)>,
}

/// A structure returning the result of a compilation.
pub struct Compilation<'cfg> {
    /// A mapping from a package to the list of libraries that need to be
    /// linked when working with that package.
    // TODO: deprecated, remove
    pub libraries: HashMap<PackageId, HashSet<(Target, PathBuf)>>,

    /// An array of all tests created during this compilation.
    pub tests: Vec<(Package, TargetKind, String, PathBuf)>,

    /// An array of all binaries created.
    pub binaries: Vec<PathBuf>,

    /// All directories for the output of native build commands.
    ///
    /// This is currently used to drive some entries which are added to the
    /// LD_LIBRARY_PATH as appropriate.
    ///
    /// The order should be deterministic.
    // TODO: deprecated, remove
    pub native_dirs: BTreeSet<PathBuf>,

    /// Root output directory (for the local package's artifacts)
    pub root_output: PathBuf,

    /// Output directory for rust dependencies.
    /// May be for the host or for a specific target.
    pub deps_output: PathBuf,

    /// Output directory for the rust host dependencies.
    pub host_deps_output: PathBuf,

    /// The path to rustc's own libstd
    pub host_dylib_path: Option<PathBuf>,

    /// The path to libstd for the target
    pub target_dylib_path: Option<PathBuf>,

    /// Extra environment variables that were passed to compilations and should
    /// be passed to future invocations of programs.
    pub extra_env: HashMap<PackageId, Vec<(String, String)>>,

    /// Libraries to test with rustdoc.
    pub to_doc_test: Vec<Doctest>,

    /// Features per package enabled during this compilation.
    pub cfgs: HashMap<PackageId, HashSet<String>>,

    /// Flags to pass to rustdoc when invoked from cargo test, per package.
    pub rustdocflags: HashMap<PackageId, Vec<String>>,

    pub host: String,
    pub target: String,

    config: &'cfg Config,
    rustc_process: ProcessBuilder,

    target_runner: Option<(PathBuf, Vec<String>)>,
}

impl<'cfg> Compilation<'cfg> {
    pub fn new<'a>(bcx: &BuildContext<'a, 'cfg>) -> CargoResult<Compilation<'cfg>> {
        // If we're using cargo as a rustc wrapper then we're in a situation
        // like `cargo fix`. For now just disregard the `RUSTC_WRAPPER` env var
        // (which is typically set to `sccache` for now). Eventually we'll
        // probably want to implement `RUSTC_WRAPPER` for `cargo fix`, but we'll
        // leave that open as a bug for now.
        let mut rustc = if bcx.build_config.cargo_as_rustc_wrapper {
            let mut rustc = bcx.rustc.process_no_wrapper();
            let prog = rustc.get_program().to_owned();
            rustc.env("RUSTC", prog);
            rustc.program(env::current_exe()?);
            rustc
        } else {
            bcx.rustc.process()
        };
        for (k, v) in bcx.build_config.extra_rustc_env.iter() {
            rustc.env(k, v);
        }
        for arg in bcx.build_config.extra_rustc_args.iter() {
            rustc.arg(arg);
        }
        let srv = bcx.build_config.rustfix_diagnostic_server.borrow();
        if let Some(server) = &*srv {
            server.configure(&mut rustc);
        }
        Ok(Compilation {
            libraries: HashMap::new(),
            native_dirs: BTreeSet::new(), // TODO: deprecated, remove
            root_output: PathBuf::from("/"),
            deps_output: PathBuf::from("/"),
            host_deps_output: PathBuf::from("/"),
            host_dylib_path: bcx.host_info.sysroot_libdir.clone(),
            target_dylib_path: bcx.target_info.sysroot_libdir.clone(),
            tests: Vec::new(),
            binaries: Vec::new(),
            extra_env: HashMap::new(),
            to_doc_test: Vec::new(),
            cfgs: HashMap::new(),
            rustdocflags: HashMap::new(),
            config: bcx.config,
            rustc_process: rustc,
            host: bcx.host_triple().to_string(),
            target: bcx.target_triple().to_string(),
            target_runner: target_runner(&bcx)?,
        })
    }

    /// See `process`.
    pub fn rustc_process(&self, pkg: &Package, target: &Target) -> CargoResult<ProcessBuilder> {
        let mut p = self.fill_env(self.rustc_process.clone(), pkg, true)?;
        if target.edition() != Edition::Edition2015 {
            p.arg(format!("--edition={}", target.edition()));
        }
        Ok(p)
    }

    /// See `process`.
    pub fn rustdoc_process(&self, pkg: &Package, target: &Target) -> CargoResult<ProcessBuilder> {
        let mut p = self.fill_env(process(&*self.config.rustdoc()?), pkg, false)?;
        if target.edition() != Edition::Edition2015 {
            p.arg("-Zunstable-options");
            p.arg(format!("--edition={}", target.edition()));
        }
        Ok(p)
    }

    /// See `process`.
    pub fn host_process<T: AsRef<OsStr>>(
        &self,
        cmd: T,
        pkg: &Package,
    ) -> CargoResult<ProcessBuilder> {
        self.fill_env(process(cmd), pkg, true)
    }

    fn target_runner(&self) -> &Option<(PathBuf, Vec<String>)> {
        &self.target_runner
    }

    /// See `process`.
    pub fn target_process<T: AsRef<OsStr>>(
        &self,
        cmd: T,
        pkg: &Package,
    ) -> CargoResult<ProcessBuilder> {
        let builder = if let Some((ref runner, ref args)) = *self.target_runner() {
            let mut builder = process(runner);
            builder.args(args);
            builder.arg(cmd);
            builder
        } else {
            process(cmd)
        };
        self.fill_env(builder, pkg, false)
    }

    /// Prepares a new process with an appropriate environment to run against
    /// the artifacts produced by the build process.
    ///
    /// The package argument is also used to configure environment variables as
    /// well as the working directory of the child process.
    fn fill_env(
        &self,
        mut cmd: ProcessBuilder,
        pkg: &Package,
        is_host: bool,
    ) -> CargoResult<ProcessBuilder> {
        let mut search_path = if is_host {
            let mut search_path = vec![self.host_deps_output.clone()];
            search_path.extend(self.host_dylib_path.clone());
            search_path
        } else {
            let mut search_path =
                super::filter_dynamic_search_path(self.native_dirs.iter(), &self.root_output);
            search_path.push(self.root_output.clone());
            search_path.push(self.deps_output.clone());
            search_path.extend(self.target_dylib_path.clone());
            search_path
        };

        search_path.extend(util::dylib_path().into_iter());
        let search_path = join_paths(&search_path, util::dylib_path_envvar())?;

        cmd.env(util::dylib_path_envvar(), &search_path);
        if let Some(env) = self.extra_env.get(pkg.package_id()) {
            for &(ref k, ref v) in env {
                cmd.env(k, v);
            }
        }

        let metadata = pkg.manifest().metadata();

        let cargo_exe = self.config.cargo_exe()?;
        cmd.env(::CARGO_ENV, cargo_exe);

        // When adding new environment variables depending on
        // crate properties which might require rebuild upon change
        // consider adding the corresponding properties to the hash
        // in BuildContext::target_metadata()
        cmd.env("CARGO_MANIFEST_DIR", pkg.root())
            .env("CARGO_PKG_VERSION_MAJOR", &pkg.version().major.to_string())
            .env("CARGO_PKG_VERSION_MINOR", &pkg.version().minor.to_string())
            .env("CARGO_PKG_VERSION_PATCH", &pkg.version().patch.to_string())
            .env(
                "CARGO_PKG_VERSION_PRE",
                &pre_version_component(pkg.version()),
            )
            .env("CARGO_PKG_VERSION", &pkg.version().to_string())
            .env("CARGO_PKG_NAME", &*pkg.name())
            .env(
                "CARGO_PKG_DESCRIPTION",
                metadata.description.as_ref().unwrap_or(&String::new()),
            )
            .env(
                "CARGO_PKG_HOMEPAGE",
                metadata.homepage.as_ref().unwrap_or(&String::new()),
            )
            .env("CARGO_PKG_AUTHORS", &pkg.authors().join(":"))
            .cwd(pkg.root());
        Ok(cmd)
    }
}

fn pre_version_component(v: &Version) -> String {
    if v.pre.is_empty() {
        return String::new();
    }

    let mut ret = String::new();

    for (i, x) in v.pre.iter().enumerate() {
        if i != 0 {
            ret.push('.')
        };
        ret.push_str(&x.to_string());
    }

    ret
}

fn target_runner(bcx: &BuildContext) -> CargoResult<Option<(PathBuf, Vec<String>)>> {
    let target = bcx.target_triple();

    // try target.{}.runner
    let key = format!("target.{}.runner", target);
    if let Some(v) = bcx.config.get_path_and_args(&key)? {
        return Ok(Some(v.val));
    }

    // try target.'cfg(...)'.runner
    if let Some(target_cfg) = bcx.target_info.cfg() {
        if let Some(table) = bcx.config.get_table("target")? {
            let mut matching_runner = None;

            for key in table.val.keys() {
                if CfgExpr::matches_key(key, target_cfg) {
                    let key = format!("target.{}.runner", key);
                    if let Some(runner) = bcx.config.get_path_and_args(&key)? {
                        // more than one match, error out
                        if matching_runner.is_some() {
                            bail!("several matching instances of `target.'cfg(..)'.runner` \
                                   in `.cargo/config`")
                        }

                        matching_runner = Some(runner.val);
                    }
                }
            }

            return Ok(matching_runner);
        }
    }

    Ok(None)
}
<commit_msg>Removes -Zunstable-options for rustdoc testing<commit_after>use std::collections::{BTreeSet, HashMap, HashSet};
use std::env;
use std::ffi::OsStr;
use std::path::PathBuf;

use semver::Version;

use core::{Edition, Package, PackageId, Target, TargetKind};
use util::{self, join_paths, process, CargoResult, CfgExpr, Config, ProcessBuilder};
use super::BuildContext;

pub struct Doctest {
    /// The package being doctested.
    pub package: Package,
    /// The target being tested (currently always the package's lib).
    pub target: Target,
    /// Extern dependencies needed by `rustdoc`. The path is the location of
    /// the compiled lib.
    pub deps: Vec<(String, PathBuf)>,
}

/// A structure returning the result of a compilation.
pub struct Compilation<'cfg> {
    /// A mapping from a package to the list of libraries that need to be
    /// linked when working with that package.
    // TODO: deprecated, remove
    pub libraries: HashMap<PackageId, HashSet<(Target, PathBuf)>>,

    /// An array of all tests created during this compilation.
    pub tests: Vec<(Package, TargetKind, String, PathBuf)>,

    /// An array of all binaries created.
    pub binaries: Vec<PathBuf>,

    /// All directories for the output of native build commands.
    ///
    /// This is currently used to drive some entries which are added to the
    /// LD_LIBRARY_PATH as appropriate.
    ///
    /// The order should be deterministic.
    // TODO: deprecated, remove
    pub native_dirs: BTreeSet<PathBuf>,

    /// Root output directory (for the local package's artifacts)
    pub root_output: PathBuf,

    /// Output directory for rust dependencies.
    /// May be for the host or for a specific target.
    pub deps_output: PathBuf,

    /// Output directory for the rust host dependencies.
    pub host_deps_output: PathBuf,

    /// The path to rustc's own libstd
    pub host_dylib_path: Option<PathBuf>,

    /// The path to libstd for the target
    pub target_dylib_path: Option<PathBuf>,

    /// Extra environment variables that were passed to compilations and should
    /// be passed to future invocations of programs.
    pub extra_env: HashMap<PackageId, Vec<(String, String)>>,

    /// Libraries to test with rustdoc.
    pub to_doc_test: Vec<Doctest>,

    /// Features per package enabled during this compilation.
    pub cfgs: HashMap<PackageId, HashSet<String>>,

    /// Flags to pass to rustdoc when invoked from cargo test, per package.
    pub rustdocflags: HashMap<PackageId, Vec<String>>,

    pub host: String,
    pub target: String,

    config: &'cfg Config,
    rustc_process: ProcessBuilder,

    target_runner: Option<(PathBuf, Vec<String>)>,
}

impl<'cfg> Compilation<'cfg> {
    pub fn new<'a>(bcx: &BuildContext<'a, 'cfg>) -> CargoResult<Compilation<'cfg>> {
        // If we're using cargo as a rustc wrapper then we're in a situation
        // like `cargo fix`. For now just disregard the `RUSTC_WRAPPER` env var
        // (which is typically set to `sccache` for now). Eventually we'll
        // probably want to implement `RUSTC_WRAPPER` for `cargo fix`, but we'll
        // leave that open as a bug for now.
        let mut rustc = if bcx.build_config.cargo_as_rustc_wrapper {
            let mut rustc = bcx.rustc.process_no_wrapper();
            let prog = rustc.get_program().to_owned();
            rustc.env("RUSTC", prog);
            rustc.program(env::current_exe()?);
            rustc
        } else {
            bcx.rustc.process()
        };
        for (k, v) in bcx.build_config.extra_rustc_env.iter() {
            rustc.env(k, v);
        }
        for arg in bcx.build_config.extra_rustc_args.iter() {
            rustc.arg(arg);
        }
        let srv = bcx.build_config.rustfix_diagnostic_server.borrow();
        if let Some(server) = &*srv {
            server.configure(&mut rustc);
        }
        Ok(Compilation {
            libraries: HashMap::new(),
            native_dirs: BTreeSet::new(), // TODO: deprecated, remove
            root_output: PathBuf::from("/"),
            deps_output: PathBuf::from("/"),
            host_deps_output: PathBuf::from("/"),
            host_dylib_path: bcx.host_info.sysroot_libdir.clone(),
            target_dylib_path: bcx.target_info.sysroot_libdir.clone(),
            tests: Vec::new(),
            binaries: Vec::new(),
            extra_env: HashMap::new(),
            to_doc_test: Vec::new(),
            cfgs: HashMap::new(),
            rustdocflags: HashMap::new(),
            config: bcx.config,
            rustc_process: rustc,
            host: bcx.host_triple().to_string(),
            target: bcx.target_triple().to_string(),
            target_runner: target_runner(&bcx)?,
        })
    }

    /// See `process`.
    pub fn rustc_process(&self, pkg: &Package, target: &Target) -> CargoResult<ProcessBuilder> {
        let mut p = self.fill_env(self.rustc_process.clone(), pkg, true)?;
        if target.edition() != Edition::Edition2015 {
            p.arg(format!("--edition={}", target.edition()));
        }
        Ok(p)
    }

    /// See `process`.
    pub fn rustdoc_process(&self, pkg: &Package, target: &Target) -> CargoResult<ProcessBuilder> {
        let mut p = self.fill_env(process(&*self.config.rustdoc()?), pkg, false)?;
        if target.edition() != Edition::Edition2015 {
            p.arg(format!("--edition={}", target.edition()));
        }
        Ok(p)
    }

    /// See `process`.
    pub fn host_process<T: AsRef<OsStr>>(
        &self,
        cmd: T,
        pkg: &Package,
    ) -> CargoResult<ProcessBuilder> {
        self.fill_env(process(cmd), pkg, true)
    }

    fn target_runner(&self) -> &Option<(PathBuf, Vec<String>)> {
        &self.target_runner
    }

    /// See `process`.
    pub fn target_process<T: AsRef<OsStr>>(
        &self,
        cmd: T,
        pkg: &Package,
    ) -> CargoResult<ProcessBuilder> {
        let builder = if let Some((ref runner, ref args)) = *self.target_runner() {
            let mut builder = process(runner);
            builder.args(args);
            builder.arg(cmd);
            builder
        } else {
            process(cmd)
        };
        self.fill_env(builder, pkg, false)
    }

    /// Prepares a new process with an appropriate environment to run against
    /// the artifacts produced by the build process.
    ///
    /// The package argument is also used to configure environment variables as
    /// well as the working directory of the child process.
    fn fill_env(
        &self,
        mut cmd: ProcessBuilder,
        pkg: &Package,
        is_host: bool,
    ) -> CargoResult<ProcessBuilder> {
        let mut search_path = if is_host {
            let mut search_path = vec![self.host_deps_output.clone()];
            search_path.extend(self.host_dylib_path.clone());
            search_path
        } else {
            let mut search_path =
                super::filter_dynamic_search_path(self.native_dirs.iter(), &self.root_output);
            search_path.push(self.root_output.clone());
            search_path.push(self.deps_output.clone());
            search_path.extend(self.target_dylib_path.clone());
            search_path
        };

        search_path.extend(util::dylib_path().into_iter());
        let search_path = join_paths(&search_path, util::dylib_path_envvar())?;

        cmd.env(util::dylib_path_envvar(), &search_path);
        if let Some(env) = self.extra_env.get(pkg.package_id()) {
            for &(ref k, ref v) in env {
                cmd.env(k, v);
            }
        }

        let metadata = pkg.manifest().metadata();

        let cargo_exe = self.config.cargo_exe()?;
        cmd.env(::CARGO_ENV, cargo_exe);

        // When adding new environment variables depending on
        // crate properties which might require rebuild upon change
        // consider adding the corresponding properties to the hash
        // in BuildContext::target_metadata()
        cmd.env("CARGO_MANIFEST_DIR", pkg.root())
            .env("CARGO_PKG_VERSION_MAJOR", &pkg.version().major.to_string())
            .env("CARGO_PKG_VERSION_MINOR", &pkg.version().minor.to_string())
            .env("CARGO_PKG_VERSION_PATCH", &pkg.version().patch.to_string())
            .env(
                "CARGO_PKG_VERSION_PRE",
                &pre_version_component(pkg.version()),
            )
            .env("CARGO_PKG_VERSION", &pkg.version().to_string())
            .env("CARGO_PKG_NAME", &*pkg.name())
            .env(
                "CARGO_PKG_DESCRIPTION",
                metadata.description.as_ref().unwrap_or(&String::new()),
            )
            .env(
                "CARGO_PKG_HOMEPAGE",
                metadata.homepage.as_ref().unwrap_or(&String::new()),
            )
            .env("CARGO_PKG_AUTHORS", &pkg.authors().join(":"))
            .cwd(pkg.root());
        Ok(cmd)
    }
}

fn pre_version_component(v: &Version) -> String {
    if v.pre.is_empty() {
        return String::new();
    }

    let mut ret = String::new();

    for (i, x) in v.pre.iter().enumerate() {
        if i != 0 {
            ret.push('.')
        };
        ret.push_str(&x.to_string());
    }

    ret
}

fn target_runner(bcx: &BuildContext) -> CargoResult<Option<(PathBuf, Vec<String>)>> {
    let target = bcx.target_triple();

    // try target.{}.runner
    let key = format!("target.{}.runner", target);
    if let Some(v) = bcx.config.get_path_and_args(&key)? {
        return Ok(Some(v.val));
    }

    // try target.'cfg(...)'.runner
    if let Some(target_cfg) = bcx.target_info.cfg() {
        if let Some(table) = bcx.config.get_table("target")? {
            let mut matching_runner = None;

            for key in table.val.keys() {
                if CfgExpr::matches_key(key, target_cfg) {
                    let key = format!("target.{}.runner", key);
                    if let Some(runner) = bcx.config.get_path_and_args(&key)? {
                        // more than one match, error out
                        if matching_runner.is_some() {
                            bail!("several matching instances of `target.'cfg(..)'.runner` \
                                   in `.cargo/config`")
                        }

                        matching_runner = Some(runner.val);
                    }
                }
            }

            return Ok(matching_runner);
        }
    }

    Ok(None)
}
<|endoftext|>


<commit_before>#[doc="High-level interface to CSS selector matching."]

import std::arc::{ARC, get, clone};

import css::values::{DisplayType, DisBlock, DisInline, DisNone, Unit, Auto};
import css::values::Stylesheet;
import dom::base::{HTMLDivElement, HTMLHeadElement, HTMLImageElement, UnknownElement, HTMLScriptElement};
import dom::base::{Comment, Doctype, Element, Node, NodeKind, Text};
import util::color::{Color, rgb};
import util::color::css_colors::{white, black};
import layout::base::{LayoutData, NTree};

type SpecifiedStyle = {mut background_color : Option<Color>,
                        mut display_type : Option<DisplayType>,
                        mut font_size : Option<Unit>,
                        mut height : Option<Unit>,
                        mut text_color : Option<Color>,
                        mut width : Option<Unit>
                       };

trait DefaultStyleMethods {
    fn default_color() -> Color;
    fn default_display_type() -> DisplayType;
    fn default_width() -> Unit;
    fn default_height() -> Unit;
}

/// Default styles for various attributes in case they don't get initialized from CSS selectors.
impl NodeKind : DefaultStyleMethods {
    fn default_color() -> Color {
        match self {
          Text(*) => white(),
          Element(*) => white(),
            _ => fail ~"unstyleable node type encountered"
        }
    }

    fn default_display_type() -> DisplayType {
        match self {
          Text(*) => { DisInline }
          Element(element) => {
            match *element.kind {
              HTMLDivElement => DisBlock,
              HTMLHeadElement => DisNone,
              HTMLImageElement(*) => DisInline,
              HTMLScriptElement => DisNone,
              UnknownElement => DisInline,
            }
          },
            _ => fail ~"unstyleable node type encountered"
        }
    }

    fn default_width() -> Unit {
        Auto
    }

    fn default_height() -> Unit {
        Auto
    }
}

/**
 * Create a specified style that can be used to initialize a node before selector matching.
 *
 * Everything is initialized to none except the display style. The default value of the display
 * style is computed so that it can be used to short-circuit selector matching to avoid computing
 * style for children of display:none objects.
 */
fn empty_style_for_node_kind(kind: NodeKind) -> SpecifiedStyle {
    let display_type = kind.default_display_type();

    {mut background_color : None,
     mut display_type : Some(display_type),
     mut font_size : None,
     mut height : None,
     mut text_color : None,
     mut width : None}
}

trait StylePriv {
    fn initialize_style() -> ~[@LayoutData];
}

impl Node : StylePriv {
    #[doc="
        Set a default auxiliary data so that other threads can modify it.

        This is, importantly, the function that creates the layout
        data for the node (the reader-auxiliary box in the RCU model)
        and populates it with the default style.

     "]
    // TODO: we should look into folding this into building the dom,
    // instead of doing a linear sweep afterwards.
    fn initialize_style() -> ~[@LayoutData] {
        if !self.has_aux() {
            let node_kind = self.read(|n| copy *n.kind);
            let the_layout_data = @LayoutData({
                mut specified_style : ~empty_style_for_node_kind(node_kind),
                mut box : None
            });

            self.set_aux(the_layout_data);

            ~[the_layout_data]
        } else {
            ~[]
        }
    }
}

trait StyleMethods {
    fn initialize_style_for_subtree() -> ~[@LayoutData];
    fn get_specified_style() -> SpecifiedStyle;
    fn recompute_style_for_subtree(styles : ARC<Stylesheet>);
}

impl Node : StyleMethods {
    #[doc="Sequentially initialize the nodes' auxilliary data so they can be updated in parallel."]
    fn initialize_style_for_subtree() -> ~[@LayoutData] {
        let mut handles = self.initialize_style();

        for NTree.each_child(self) |kid| {
            handles += kid.initialize_style_for_subtree();
        }

        return handles;
    }

    #[doc="
        Returns the computed style for the given node. If CSS selector matching has not yet been
        performed, fails.

        TODO: Return a safe reference; don't copy.
    "]
    fn get_specified_style() -> SpecifiedStyle {
        if !self.has_aux() {
            fail ~"get_specified_style() called on a node without a style!";
        }
        return copy *self.aux(|x| copy x).specified_style;
    }

    #[doc="
        Performs CSS selector matching on a subtree.

        This is, importantly, the function that updates the layout data for the node (the reader-
        auxiliary box in the RCU model) with the computed style.
    "]
    fn recompute_style_for_subtree(styles : ARC<Stylesheet>) {
        listen(|ack_chan| {
            let mut i = 0u;

            // Compute the styles of each of our children in parallel
            for NTree.each_child(self) |kid| {
                i = i + 1u;
                let new_styles = clone(&styles);

                task::spawn(|| {
                    kid.recompute_style_for_subtree(new_styles);
                    ack_chan.send(());
                })
            }

            self.match_css_style(*get(&styles));

            // Make sure we have finished updating the tree before returning
            while i > 0 {
                ack_chan.recv();
                i = i - 1u;
            }
        })
    }
}
<commit_msg>Fix default css 'display' value for undisplayed nodes.<commit_after>#[doc="High-level interface to CSS selector matching."]

import std::arc::{ARC, get, clone};

import css::values::{DisplayType, DisBlock, DisInline, DisNone, Unit, Auto};
import css::values::Stylesheet;
import dom::base::{HTMLDivElement, HTMLHeadElement, HTMLImageElement, UnknownElement, HTMLScriptElement};
import dom::base::{Comment, Doctype, Element, Node, NodeKind, Text};
import util::color::{Color, rgb};
import util::color::css_colors::{white, black};
import layout::base::{LayoutData, NTree};

type SpecifiedStyle = {mut background_color : Option<Color>,
                        mut display_type : Option<DisplayType>,
                        mut font_size : Option<Unit>,
                        mut height : Option<Unit>,
                        mut text_color : Option<Color>,
                        mut width : Option<Unit>
                       };

trait DefaultStyleMethods {
    fn default_color() -> Color;
    fn default_display_type() -> DisplayType;
    fn default_width() -> Unit;
    fn default_height() -> Unit;
}

/// Default styles for various attributes in case they don't get initialized from CSS selectors.
impl NodeKind : DefaultStyleMethods {
    fn default_color() -> Color {
        match self {
          Text(*) => white(),
          Element(*) => white(),
            _ => fail ~"unstyleable node type encountered"
        }
    }

    fn default_display_type() -> DisplayType {
        match self {
          Text(*) => { DisInline }
          Element(element) => {
            match *element.kind {
              HTMLDivElement => DisBlock,
              HTMLHeadElement => DisNone,
              HTMLImageElement(*) => DisInline,
              HTMLScriptElement => DisNone,
              UnknownElement => DisInline,
            }
          },
          Comment(*) | Doctype(*) => DisNone
        }
    }

    fn default_width() -> Unit {
        Auto
    }

    fn default_height() -> Unit {
        Auto
    }
}

/**
 * Create a specified style that can be used to initialize a node before selector matching.
 *
 * Everything is initialized to none except the display style. The default value of the display
 * style is computed so that it can be used to short-circuit selector matching to avoid computing
 * style for children of display:none objects.
 */
fn empty_style_for_node_kind(kind: NodeKind) -> SpecifiedStyle {
    let display_type = kind.default_display_type();

    {mut background_color : None,
     mut display_type : Some(display_type),
     mut font_size : None,
     mut height : None,
     mut text_color : None,
     mut width : None}
}

trait StylePriv {
    fn initialize_style() -> ~[@LayoutData];
}

impl Node : StylePriv {
    #[doc="
        Set a default auxiliary data so that other threads can modify it.

        This is, importantly, the function that creates the layout
        data for the node (the reader-auxiliary box in the RCU model)
        and populates it with the default style.

     "]
    // TODO: we should look into folding this into building the dom,
    // instead of doing a linear sweep afterwards.
    fn initialize_style() -> ~[@LayoutData] {
        if !self.has_aux() {
            let node_kind = self.read(|n| copy *n.kind);
            let the_layout_data = @LayoutData({
                mut specified_style : ~empty_style_for_node_kind(node_kind),
                mut box : None
            });

            self.set_aux(the_layout_data);

            ~[the_layout_data]
        } else {
            ~[]
        }
    }
}

trait StyleMethods {
    fn initialize_style_for_subtree() -> ~[@LayoutData];
    fn get_specified_style() -> SpecifiedStyle;
    fn recompute_style_for_subtree(styles : ARC<Stylesheet>);
}

impl Node : StyleMethods {
    #[doc="Sequentially initialize the nodes' auxilliary data so they can be updated in parallel."]
    fn initialize_style_for_subtree() -> ~[@LayoutData] {
        let mut handles = self.initialize_style();

        for NTree.each_child(self) |kid| {
            handles += kid.initialize_style_for_subtree();
        }

        return handles;
    }

    #[doc="
        Returns the computed style for the given node. If CSS selector matching has not yet been
        performed, fails.

        TODO: Return a safe reference; don't copy.
    "]
    fn get_specified_style() -> SpecifiedStyle {
        if !self.has_aux() {
            fail ~"get_specified_style() called on a node without a style!";
        }
        return copy *self.aux(|x| copy x).specified_style;
    }

    #[doc="
        Performs CSS selector matching on a subtree.

        This is, importantly, the function that updates the layout data for the node (the reader-
        auxiliary box in the RCU model) with the computed style.
    "]
    fn recompute_style_for_subtree(styles : ARC<Stylesheet>) {
        listen(|ack_chan| {
            let mut i = 0u;

            // Compute the styles of each of our children in parallel
            for NTree.each_child(self) |kid| {
                i = i + 1u;
                let new_styles = clone(&styles);

                task::spawn(|| {
                    kid.recompute_style_for_subtree(new_styles);
                    ack_chan.send(());
                })
            }

            self.match_css_style(*get(&styles));

            // Make sure we have finished updating the tree before returning
            while i > 0 {
                ack_chan.recv();
                i = i - 1u;
            }
        })
    }
}
<|endoftext|>


<commit_before>export Image;

export load;
export load_from_memory;
export test_image_bin;

import stb_image::image::{image, load, load_from_memory};

// FIXME: Images must not be copied every frame. Instead we should atomically
// reference count them.

type Image = image;

const TEST_IMAGE: [u8 * 88129] = #include_bin("test.jpeg");

fn test_image_bin() -> ~[u8] {
    return vec::from_fn(88129, |i| TEST_IMAGE[i]);
}
<commit_msg>Fix size of image in image/base.rs<commit_after>export Image;

export load;
export load_from_memory;
export test_image_bin;

import stb_image::image::{image, load, load_from_memory};

// FIXME: Images must not be copied every frame. Instead we should atomically
// reference count them.

type Image = image;

const TEST_IMAGE: [u8 * 4962] = #include_bin("test.jpeg");

fn test_image_bin() -> ~[u8] {
    return vec::from_fn(4962, |i| TEST_IMAGE[i]);
}
<|endoftext|>


<commit_before>export Image;

export load;
export load_from_memory;
export test_image_bin;

use stb_image = stb_image::Image;

// FIXME: Images must not be copied every frame. Instead we should atomically
// reference count them.

type Image = stb_image::Image;

fn Image(width: uint, height: uint, depth: uint, +data: ~[u8]) -> Image {
    stb_image::new_image(width, height, depth, data)
}

const TEST_IMAGE: [u8 * 4962] = #include_bin("test.jpeg");

fn test_image_bin() -> ~[u8] {
    return vec::from_fn(4962, |i| TEST_IMAGE[i]);
}

fn load_from_memory(buffer: &[u8]) -> Option<Image> {
    do stb_image::load_from_memory(buffer).map |image| {

        assert image.depth == 4;
        // Do color space conversion :(
        let data = do vec::from_fn(image.width * image.height * 4) |i| {
            let color = i % 4;
            let pixel = i / 4;
            match color {
              0 => image.data[pixel * 4 + 2],
              1 => image.data[pixel * 4 + 1],
              2 => image.data[pixel * 4 + 0],
              3 => 0xffu8,
              _ => fail
            }
        };

        assert image.data.len() == data.len();

       Image(image.width, image.height, image.depth, data)
    }
}
<commit_msg>Fix name of stb_image::image mod<commit_after>export Image;

export load;
export load_from_memory;
export test_image_bin;

use stb_image = stb_image::image;

// FIXME: Images must not be copied every frame. Instead we should atomically
// reference count them.

type Image = stb_image::Image;

fn Image(width: uint, height: uint, depth: uint, +data: ~[u8]) -> Image {
    stb_image::new_image(width, height, depth, data)
}

const TEST_IMAGE: [u8 * 4962] = #include_bin("test.jpeg");

fn test_image_bin() -> ~[u8] {
    return vec::from_fn(4962, |i| TEST_IMAGE[i]);
}

fn load_from_memory(buffer: &[u8]) -> Option<Image> {
    do stb_image::load_from_memory(buffer).map |image| {

        assert image.depth == 4;
        // Do color space conversion :(
        let data = do vec::from_fn(image.width * image.height * 4) |i| {
            let color = i % 4;
            let pixel = i / 4;
            match color {
              0 => image.data[pixel * 4 + 2],
              1 => image.data[pixel * 4 + 1],
              2 => image.data[pixel * 4 + 0],
              3 => 0xffu8,
              _ => fail
            }
        };

        assert image.data.len() == data.len();

       Image(image.width, image.height, image.depth, data)
    }
}
<|endoftext|>


<commit_before><commit_msg>Factor out draw_segment_pixel fn<commit_after><|endoftext|>


<commit_before><commit_msg>minor<commit_after><|endoftext|>