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

use ops::{Add, Sub, Mul, Div};

const NANOS_PER_SEC: u32 = 1_000_000_000;
const NANOS_PER_MILLI: u32 = 1_000_000;
const MILLIS_PER_SEC: u64 = 1_000;

/// A duration type to represent a span of time, typically used for system
/// timeouts.
///
/// Each duration is composed of a number of seconds and nanosecond precision.
/// APIs binding a system timeout will typically round up the nanosecond
/// precision if the underlying system does not support that level of precision.
///
/// Durations implement many common traits, including `Add`, `Sub`, and other
/// ops traits. Currently a duration may only be inspected for its number of
/// seconds and its nanosecond precision.
///
/// # Examples
///
/// ```
/// use std::time::Duration;
///
/// let five_seconds = Duration::new(5, 0);
/// let five_seconds_and_five_nanos = five_seconds + Duration::new(0, 5);
///
/// assert_eq!(five_seconds_and_five_nanos.as_secs(), 5);
/// assert_eq!(five_seconds_and_five_nanos.subsec_nanos(), 5);
///
/// let ten_millis = Duration::from_millis(10);
/// ```
#[stable(feature = "duration", since = "1.3.0")]
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
pub struct Duration {
secs: u64,
nanos: u32, // Always 0 <= nanos < NANOS_PER_SEC
}

impl Duration {
/// Crates a new `Duration` from the specified number of seconds and
/// additional nanosecond precision.
///
/// If the nanoseconds is greater than 1 billion (the number of nanoseconds
/// in a second), then it will carry over into the seconds provided.
#[stable(feature = "duration", since = "1.3.0")]
pub fn new(secs: u64, nanos: u32) -> Duration {
let secs = secs + (nanos / NANOS_PER_SEC) as u64;
let nanos = nanos % NANOS_PER_SEC;
Duration { secs: secs, nanos: nanos }
}

/// Creates a new `Duration` from the specified number of seconds.
#[stable(feature = "duration", since = "1.3.0")]
pub fn from_secs(secs: u64) -> Duration {
Duration { secs: secs, nanos: 0 }
}

/// Creates a new `Duration` from the specified number of milliseconds.
#[stable(feature = "duration", since = "1.3.0")]
pub fn from_millis(millis: u64) -> Duration {
let secs = millis / MILLIS_PER_SEC;
let nanos = ((millis % MILLIS_PER_SEC) as u32) * NANOS_PER_MILLI;
Duration { secs: secs, nanos: nanos }
}

/// Returns the number of whole seconds represented by this duration.
///
/// The extra precision represented by this duration is ignored (e.g. extra
/// nanoseconds are not represented in the returned value).
#[stable(feature = "duration", since = "1.3.0")]
pub fn as_secs(&self) -> u64 { self.secs }

/// Returns the nanosecond precision represented by this duration.
///
/// This method does **not** return the length of the duration when
/// represented by nanoseconds. The returned number always represents a
/// fractional portion of a second (e.g. it is less than one billion).
#[stable(feature = "duration", since = "1.3.0")]
pub fn subsec_nanos(&self) -> u32 { self.nanos }
}

impl Add for Duration {
type Output = Duration;

fn add(self, rhs: Duration) -> Duration {
let mut secs = self.secs.checked_add(rhs.secs)
.expect("overflow when adding durations");
let mut nanos = self.nanos + rhs.nanos;
if nanos >= NANOS_PER_SEC {
nanos -= NANOS_PER_SEC;
secs = secs.checked_add(1).expect("overflow when adding durations");
}
debug_assert!(nanos < NANOS_PER_SEC);
Duration { secs: secs, nanos: nanos }
}
}

impl Sub for Duration {
type Output = Duration;

fn sub(self, rhs: Duration) -> Duration {
let mut secs = self.secs.checked_sub(rhs.secs)
.expect("overflow when subtracting durations");
let nanos = if self.nanos >= rhs.nanos {
self.nanos - rhs.nanos
} else {
secs = secs.checked_sub(1)
.expect("overflow when subtracting durations");
self.nanos + NANOS_PER_SEC - rhs.nanos
};
debug_assert!(nanos < NANOS_PER_SEC);
Duration { secs: secs, nanos: nanos }
}
}

impl Mul<u32> for Duration {
type Output = Duration;

fn mul(self, rhs: u32) -> Duration {
// Multiply nanoseconds as u64, because it cannot overflow that way.
let total_nanos = self.nanos as u64 * rhs as u64;
let extra_secs = total_nanos / (NANOS_PER_SEC as u64);
let nanos = (total_nanos % (NANOS_PER_SEC as u64)) as u32;
let secs = self.secs.checked_mul(rhs as u64)
.and_then(|s| s.checked_add(extra_secs))
.expect("overflow when multiplying duration");
debug_assert!(nanos < NANOS_PER_SEC);
Duration { secs: secs, nanos: nanos }
}
}

impl Div<u32> for Duration {
type Output = Duration;

fn div(self, rhs: u32) -> Duration {
let secs = self.secs / (rhs as u64);
let carry = self.secs - secs * (rhs as u64);
let extra_nanos = carry * (NANOS_PER_SEC as u64) / (rhs as u64);
let nanos = self.nanos / rhs + (extra_nanos as u32);
debug_assert!(nanos < NANOS_PER_SEC);
Duration { secs: secs, nanos: nanos }
}
}

#[cfg(test)]
mod tests {
use prelude::v1::*;
use super::Duration;

#[test]
fn creation() {
assert!(Duration::from_secs(1) != Duration::from_secs(0));
assert_eq!(Duration::from_secs(1) + Duration::from_secs(2),
Duration::from_secs(3));
assert_eq!(Duration::from_millis(10) + Duration::from_secs(4),
Duration::new(4, 10 * 1_000_000));
assert_eq!(Duration::from_millis(4000), Duration::new(4, 0));
}

#[test]
fn secs() {
assert_eq!(Duration::new(0, 0).as_secs(), 0);
assert_eq!(Duration::from_secs(1).as_secs(), 1);
assert_eq!(Duration::from_millis(999).as_secs(), 0);
assert_eq!(Duration::from_millis(1001).as_secs(), 1);
}

#[test]
fn nanos() {
assert_eq!(Duration::new(0, 0).subsec_nanos(), 0);
assert_eq!(Duration::new(0, 5).subsec_nanos(), 5);
assert_eq!(Duration::new(0, 1_000_000_001).subsec_nanos(), 1);
assert_eq!(Duration::from_secs(1).subsec_nanos(), 0);
assert_eq!(Duration::from_millis(999).subsec_nanos(), 999 * 1_000_000);
assert_eq!(Duration::from_millis(1001).subsec_nanos(), 1 * 1_000_000);
}

#[test]
fn add() {
assert_eq!(Duration::new(0, 0) + Duration::new(0, 1),
Duration::new(0, 1));
assert_eq!(Duration::new(0, 500_000_000) + Duration::new(0, 500_000_001),
Duration::new(1, 1));
}

#[test]
fn sub() {
assert_eq!(Duration::new(0, 1) - Duration::new(0, 0),
Duration::new(0, 1));
assert_eq!(Duration::new(0, 500_000_001) - Duration::new(0, 500_000_000),
Duration::new(0, 1));
assert_eq!(Duration::new(1, 0) - Duration::new(0, 1),
Duration::new(0, 999_999_999));
}

#[test] #[should_panic]
fn sub_bad1() {
Duration::new(0, 0) - Duration::new(0, 1);
}

#[test] #[should_panic]
fn sub_bad2() {
Duration::new(0, 0) - Duration::new(1, 0);
}

#[test]
fn mul() {
assert_eq!(Duration::new(0, 1) * 2, Duration::new(0, 2));
assert_eq!(Duration::new(1, 1) * 3, Duration::new(3, 3));
assert_eq!(Duration::new(0, 500_000_001) * 4, Duration::new(2, 4));
assert_eq!(Duration::new(0, 500_000_001) * 4000,
Duration::new(2000, 4000));
}

#[test]
fn div() {
assert_eq!(Duration::new(0, 1) / 2, Duration::new(0, 0));
assert_eq!(Duration::new(1, 1) / 3, Duration::new(0, 333_333_333));
assert_eq!(Duration::new(99, 999_999_000) / 100,
Duration::new(0, 999_999_990));
}
}
@@ -0,0 +1,17 @@
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

//! Temporal quantification.

#![stable(feature = "time", since = "1.3.0")]

pub use self::duration::Duration;

mod duration;
@@ -0,0 +1,11 @@
[package]
name = "coretest"
version = "1.0.0"
authors = ["The Rust Project Developers"]

[lib]
name = "coretest"
path = "lib.rs"

[dependencies]
test = { path = "../libtest" }
@@ -0,0 +1,13 @@
[package]
name = "flate"
version = "1.0.0"
authors = ["The Rust Project Developers"]
links = "miniz"
build = "build.rs"

[lib]
name = "flate"
path = "lib.rs"

[build-dependencies]
gcc = "0.3"
@@ -0,0 +1,9 @@
extern crate gcc;

fn main() {
let sources = &[
"../rt/miniz.c",
];

gcc::compile_library("libminiz.a", sources);
}
@@ -0,0 +1,8 @@
[package]
name = "fmt_macros"
version = "1.0.0"
authors = ["The Rust Project Developers"]

[lib]
name = "fmt_macros"
path = "lib.rs"
@@ -0,0 +1,8 @@
[package]
name = "getopts"
version = "1.0.0"
authors = ["The Rust Project Developers"]

[lib]
name = "getopts"
path = "lib.rs"
@@ -0,0 +1,8 @@
[package]
name = "graphviz"
version = "1.0.0"
authors = ["The Rust Project Developers"]

[lib]
name = "graphviz"
path = "lib.rs"
@@ -0,0 +1,11 @@
[package]
name = "libc"
version = "1.0.0"
authors = ["The Project Rust Developers"]

[lib]
name = "libc"
path = "lib.rs"

[dependencies]
core = { path = "../libcore" }
@@ -2592,6 +2592,97 @@ pub mod types {
}
}
}

#[cfg(target_os = "none")]
pub mod os {
pub mod common {
pub mod posix01 {
use types::os::arch::c95::{time_t, suseconds_t, c_long};

#[repr(C)]
#[derive(Copy, Clone)] pub struct timeval {
pub tv_sec: time_t,
pub tv_usec: suseconds_t,
}

#[repr(C)]
#[derive(Copy, Clone)] pub struct timespec {
pub tv_sec: time_t,
pub tv_nsec: c_long,
}

pub enum timezone {}
}
pub mod bsd43 { }
pub mod bsd44 { }
}

pub mod arch {
pub mod c95 {
use types::os::arch::posix88::ssize_t;
pub type c_char = i8;
pub type c_schar = i8;
pub type c_uchar = u8;
pub type c_short = i16;
pub type c_ushort = u16;
pub type c_int = i32;
pub type c_uint = u32;
pub type c_long = ssize_t;
pub type c_ulong = size_t;
pub type c_float = f32;
pub type c_double = f64;
#[cfg(target_pointer_width = "32")]
pub type size_t = u32;
#[cfg(target_pointer_width = "64")]
pub type size_t = u64;
pub type ptrdiff_t = ssize_t;
pub type clock_t = ssize_t;
pub type time_t = ssize_t;
pub type suseconds_t = ssize_t;
pub type wchar_t = i32;
}
pub mod c99 {
use types::os::arch::c95::size_t;
use types::os::arch::posix88::ssize_t;
pub type c_longlong = i64;
pub type c_ulonglong = u64;
pub type intptr_t = ssize_t;
pub type uintptr_t = size_t;
pub type intmax_t = i64;
pub type uintmax_t = u64;
}
pub mod posix88 {
use types::os::arch::c95::size_t;
pub type off_t = ssize_t;
pub type dev_t = u64;
pub type ino_t = size_t;

pub type pid_t = i32;
pub type uid_t = u32;
pub type gid_t = u32;
pub type useconds_t = size_t;

pub type mode_t = u32;
#[cfg(target_pointer_width = "32")]
pub type ssize_t = i32;
#[cfg(target_pointer_width = "64")]
pub type ssize_t = i64;
}
pub mod posix01 {
use types::os::arch::c95::time_t;

#[repr(C)]
#[derive(Copy, Clone)] pub struct utimbuf {
pub actime: time_t,
pub modtime: time_t,
}
}

pub mod posix08 { }
pub mod bsd44 { }
pub mod extra { }
}
}
}

pub mod consts {
@@ -5874,6 +5965,19 @@ pub mod consts {
pub const _PC_PATH_MAX: c_int = 5;
}
}

#[cfg(target_os = "none")]
pub mod os {
pub mod c95 { }
pub mod c99 { }
pub mod posix88 { }

pub mod posix01 { }
pub mod posix08 { }
pub mod bsd44 { }
pub mod sysconf { }
pub mod extra { }
}
}


@@ -6636,7 +6740,7 @@ pub mod funcs {
}
}

#[cfg(not(windows))]
#[cfg(all(not(windows), not(target_os = "none")))]
pub mod bsd43 {
use types::common::c95::{c_void};
use types::os::common::bsd44::{socklen_t, sockaddr, ifaddrs};
@@ -7037,6 +7141,41 @@ pub mod funcs {
}
}
}

#[cfg(target_os = "none")]
pub mod posix88 {
pub mod stat_ { }
pub mod stdio { }
pub mod net { }
pub mod fcntl { }
pub mod dirent { }
pub mod unistd { }
pub mod mman { }
}

#[cfg(target_os = "none")]
pub mod posix01 {
pub mod stat_ { }
pub mod unistd { }
pub mod resource { }
pub mod glob { }
pub mod mman { }
pub mod net { }
}

#[cfg(target_os = "none")]
pub mod posix08 {
pub mod unistd { }
}

#[cfg(target_os = "none")]
pub mod bsd43 { }

#[cfg(target_os = "none")]
pub mod bsd44 { }

#[cfg(target_os = "none")]
pub mod extra { }
}

#[test] fn work_on_windows() { } // FIXME #10872 needed for a happy windows
@@ -0,0 +1,8 @@
[package]
name = "log"
version = "1.0.0"
authors = ["The Rust Project Developers"]

[lib]
name = "log"
path = "lib.rs"
@@ -0,0 +1,11 @@
[package]
name = "rand"
version = "1.0.0"
authors = ["The Rust Project Developers"]

[lib]
name = "rand"
path = "lib.rs"

[dependencies]
core = { path = "../libcore" }
@@ -0,0 +1,12 @@
[package]
name = "rbml"
version = "1.0.0"
authors = ["The Rust Project Developers"]

[lib]
name = "rbml"
path = "lib.rs"

[dependencies]
serialize = { path = "../libserialize" }
log = { path = "../liblog" }
@@ -0,0 +1,14 @@
[package]
name = "rustc"
version = "1.0.0"
authors = ["The Rust Project Developers"]

[lib]
name = "rustc"
path = "lib.rs"

[dependencies]
rustc_llvm = { path = "../librustc_llvm" }
rustc_back = { path = "../librustc_back" }
rustc_front = { path = "../librustc_front" }
rustc_data_structures = { path = "../librustc_data_structures" }
@@ -32,7 +32,7 @@
#![feature(collections)]
#![feature(const_fn)]
#![feature(core)]
#![feature(duration_span)]
#![feature(time_span)]
#![feature(dynamic_lib)]
#![feature(enumset)]
#![feature(fs_canonicalize)]
@@ -235,7 +235,7 @@ use std::io;
use std::path::{Path, PathBuf};
use std::ptr;
use std::slice;
use std::time::Duration;
use std::time;

use flate;

@@ -722,7 +722,7 @@ impl ArchiveMetadata {
fn get_metadata_section(target: &Target, filename: &Path)
-> Result<MetadataBlob, String> {
let mut ret = None;
let dur = Duration::span(|| {
let dur = time::span(|| {
ret = Some(get_metadata_section_imp(target, filename));
});
info!("reading {:?} => {:?}", filename.file_name().unwrap(), dur);
@@ -610,9 +610,10 @@ pub fn default_configuration(sess: &Session) -> ast::CrateConfig {
let env = &sess.target.target.target_env;
let vendor = &sess.target.target.target_vendor;

let fam = match sess.target.target.options.is_like_windows {
true => InternedString::new("windows"),
false => InternedString::new("unix")
let fam = match (&sess.target.target.options.target_family, sess.target.target.options.is_like_windows) {
(&Some(ref fam), _) => intern(fam),
(_, true) => InternedString::new("windows"),
(_, false) => InternedString::new("unix")
};

let mk = attr::mk_name_value_item_str;
@@ -18,7 +18,7 @@ use std::fmt::Debug;
use std::hash::Hash;
use std::iter::repeat;
use std::path::Path;
use std::time::Duration;
use std::time;

use rustc_front::hir;
use rustc_front::visit;
@@ -48,7 +48,7 @@ pub fn time<T, F>(do_it: bool, what: &str, f: F) -> T where
let dur = {
let ref mut rvp = rv;

Duration::span(move || {
time::span(move || {
*rvp = Some(f())
})
};
@@ -0,0 +1,12 @@
[package]
name = "rustc_back"
version = "1.0.0"
authors = ["The Rust Project Developers"]

[lib]
name = "rustc_back"
path = "lib.rs"

[dependencies]
rustc_llvm = { path = "../librustc_llvm" }
rustc_front = { path = "../librustc_front" }
@@ -141,6 +141,8 @@ pub struct TargetOptions {
pub staticlib_prefix: String,
/// String to append to the name of every static library. Defaults to ".a".
pub staticlib_suffix: String,
/// OS family to use for conditional compilation. Valid options: "unix", "windows".
pub target_family: Option<String>,
/// Whether the target toolchain is like OSX's. Only useful for compiling against iOS/OS X, in
/// particular running dsymutil and some other stuff like `-dead_strip`. Defaults to false.
pub is_like_osx: bool,
@@ -210,6 +212,7 @@ impl Default for TargetOptions {
exe_suffix: "".to_string(),
staticlib_prefix: "lib".to_string(),
staticlib_suffix: ".a".to_string(),
target_family: None,
is_like_osx: false,
is_like_windows: false,
is_like_android: false,
@@ -326,6 +329,7 @@ impl Target {
key!(disable_redzone, bool);
key!(eliminate_frame_pointer, bool);
key!(function_sections, bool);
key!(target_family, optional);
key!(is_like_osx, bool);
key!(is_like_windows, bool);
key!(linker_is_gnu, bool);
@@ -0,0 +1,11 @@
[package]
name = "rustc_bitflags"
version = "1.0.0"
authors = ["The Rust Project Developers"]

[lib]
name = "rustc_bitflags"
path = "lib.rs"

[dependencies]
core = { path = "../libcore" }
@@ -0,0 +1,12 @@
[package]
name = "rustc_borrowck"
version = "1.0.0"
authors = ["The Rust Project Developers"]

[lib]
name = "rustc_borrowck"
path = "lib.rs"

[dependencies]
rustc = { path = "../librustc" }
rustc_front = { path = "../librustc_front" }
@@ -0,0 +1,8 @@
[package]
name = "rustc_data_structures"
version = "1.0.0"
authors = ["The Rust Project Developers"]

[lib]
name = "rustc_data_structures"
path = "lib.rs"
@@ -0,0 +1,26 @@
[package]
name = "rustc_driver"
version = "1.0.0"
authors = ["The Rust Project Developers"]
build = "build.rs"

[lib]
name = "rustc_driver"
path = "lib.rs"

[[bin]]
name = "rustc"
path = "../driver/driver.rs"

[dependencies]
rustc = { path = "../librustc" }
rustc_back = { path = "../librustc_back" }
rustc_borrowck = { path = "../librustc_borrowck" }
rustc_front = { path = "../librustc_front" }
rustc_lint = { path = "../librustc_lint" }
rustc_privacy = { path = "../librustc_privacy" }
rustc_mir = { path = "../librustc_mir" }
rustc_resolve = { path = "../librustc_resolve" }
rustc_trans = { path = "../librustc_trans" }
rustc_typeck = { path = "../librustc_typeck" }
rustc_llvm = { path = "../librustc_llvm" }
@@ -0,0 +1,3 @@
fn main() {
println!("cargo:rustc-cfg=rustc")
}
@@ -0,0 +1,8 @@
[package]
name = "rustc_front"
version = "1.0.0"
authors = ["The Rust Project Developers"]

[lib]
name = "rustc_front"
path = "lib.rs"
@@ -0,0 +1,12 @@
[package]
name = "rustc_lint"
version = "1.0.0"
authors = ["The Rust Project Developers"]

[lib]
name = "rustc_lint"
path = "lib.rs"

[dependencies]
rustc = { path = "../librustc" }
rustc_front = { path = "../librustc_front" }
@@ -0,0 +1,12 @@
[package]
name = "rustc_llvm"
version = "1.0.0"
authors = ["The Rust Project Developers"]
build = "build.rs"

[lib]
name = "rustc_llvm"
path = "lib.rs"

[build-dependencies]
gcc = "0.3"
@@ -0,0 +1,48 @@
use std::process::Command;
use std::path::PathBuf;
use std::env;

extern crate gcc;

fn main() {
let dir = env::current_dir().unwrap();
let llvmdeps = PathBuf::from(&env::var_os("CFG_LLVM_LINKAGE_FILE").unwrap());
let llvm_config = PathBuf::from(&env::var_os("CFG_LLVM_CONFIG").unwrap());
let std_cpp = PathBuf::from(&env::var_os("CFG_LLVM_STDCPP").unwrap());

let sources = &[
"../rustllvm/ArchiveWrapper.cpp",
"../rustllvm/ExecutionEngineWrapper.cpp",
"../rustllvm/PassWrapper.cpp",
"../rustllvm/RustWrapper.cpp",
];

let mklldeps = dir.join("../etc/mklldeps.py");

run(Command::new("python2")
.arg(mklldeps)
.arg(llvmdeps)
.arg("")
.arg("1")
.arg(&llvm_config)
.arg(std_cpp));

println!("cargo:rustc-link-lib=ffi");
println!("cargo:rustc-link-search=native={}", String::from_utf8(Command::new(llvm_config).arg("--libdir").output().unwrap().stdout).unwrap());

let mut config = gcc::Config::new();
config.flag("-std=c++11");
compile_library("librustllvm.a", sources, config);
}

fn run(cmd: &mut Command) {
println!("running: {:?}", cmd);
cmd.status().unwrap();
}

fn compile_library(output: &str, files: &[&str], mut c: gcc::Config) {
for f in files.iter() {
c.file(*f);
}
c.compile(output)
}
@@ -0,0 +1,13 @@
[package]
name = "rustc_mir"
version = "1.0.0"
authors = ["The Rust Project Developers"]

[lib]
name = "rustc_mir"
path = "lib.rs"

[dependencies]
rustc = { path = "../librustc" }
rustc_data_structures = { path = "../librustc_data_structures" }
rustc_front = { path = "../librustc_front" }
@@ -0,0 +1,12 @@
[package]
name = "rustc_platform_intrinsics"
version = "1.0.0"
authors = ["The Rust Project Developers"]

[lib]
name = "rustc_platform_intrinsics"
path = "lib.rs"

[dependencies]
rustc = { path = "../librustc" }
rustc_llvm = { path = "../librustc_llvm" }
@@ -0,0 +1,12 @@
[package]
name = "rustc_privacy"
version = "1.0.0"
authors = ["The Rust Project Developers"]

[lib]
name = "rustc_privacy"
path = "lib.rs"

[dependencies]
rustc = { path = "../librustc" }
rustc_front = { path = "../librustc_front" }
@@ -0,0 +1,12 @@
[package]
name = "rustc_resolve"
version = "1.0.0"
authors = ["The Rust Project Developers"]

[lib]
name = "rustc_resolve"
path = "lib.rs"

[dependencies]
rustc = { path = "../librustc" }
rustc_front = { path = "../librustc_front" }
@@ -0,0 +1,15 @@
[package]
name = "rustc_trans"
version = "1.0.0"
authors = ["The Rust Project Developers"]

[lib]
name = "rustc_trans"
path = "lib.rs"

[dependencies]
rustc = { path = "../librustc" }
rustc_back = { path = "../librustc_back" }
rustc_front = { path = "../librustc_front" }
rustc_llvm = { path = "../librustc_llvm" }
rustc_platform_intrinsics = { path = "../librustc_platform_intrinsics" }
@@ -0,0 +1,13 @@
[package]
name = "rustc_typeck"
version = "1.0.0"
authors = ["The Rust Project Developers"]

[lib]
name = "rustc_typeck"
path = "lib.rs"

[dependencies]
rustc = { path = "../librustc" }
rustc_front = { path = "../librustc_front" }
rustc_platform_intrinsics = { path = "../librustc_platform_intrinsics" }
@@ -0,0 +1,11 @@
[package]
name = "rustc_unicode"
version = "1.0.0"
authors = ["The Rust Project Developers"]

[lib]
name = "rustc_unicode"
path = "lib.rs"

[dependencies]
core = { path = "../libcore" }
@@ -0,0 +1,24 @@
[package]
name = "rustdoc"
version = "1.0.0"
authors = ["The Rust Project Developers"]
build = "build.rs"

[lib]
name = "rustdoc"
path = "lib.rs"

[[bin]]
name = "rustdoc"
path = "../driver/driver.rs"

[dependencies]
rustc_trans = { path = "../librustc_trans" }
rustc_driver = { path = "../librustc_driver" }
rustc_resolve = { path = "../librustc_resolve" }
rustc_lint = { path = "../librustc_lint" }
rustc_back = { path = "../librustc_back" }
rustc_front = { path = "../librustc_front" }

[build-dependencies]
gcc = "0.3"
@@ -0,0 +1,19 @@
extern crate gcc;

fn main() {
let sources = &[
"../rt/hoedown/src/autolink.c",
"../rt/hoedown/src/buffer.c",
"../rt/hoedown/src/document.c",
"../rt/hoedown/src/escape.c",
"../rt/hoedown/src/html.c",
"../rt/hoedown/src/html_blocks.c",
"../rt/hoedown/src/html_smartypants.c",
"../rt/hoedown/src/stack.c",
"../rt/hoedown/src/version.c",
];

gcc::compile_library("libhoedown.a", sources);

println!("cargo:rustc-cfg=rustdoc")
}
@@ -0,0 +1,11 @@
[package]
name = "serialize"
version = "1.0.0"
authors = ["The Rust Project Developers"]

[lib]
name = "serialize"
path = "lib.rs"

[dependencies]
log = { path = "../liblog" }
@@ -0,0 +1,26 @@
[package]
name = "std"
version = "1.0.0"
authors = ["The Rust Project Developers"]

[lib]
name = "std"
path = "lib.rs"

[dependencies]
core = { path = "../libcore" }
alloc = { path = "../liballoc" }
rand = { path = "../librand" }
system = { path = "../libsystem", default-features = false }
collections = { path = "../libcollections" }
rustc_unicode = { path = "../librustc_unicode" }
rustc_bitflags = { path = "../librustc_bitflags" }

[dev-dependencies]
test = { path = "../libtest" }

[features]
default = ["compiler-rt", "backtrace", "rust_builtin"]
compiler-rt = ["system/compiler-rt"]
backtrace = ["system/backtrace"]
rust_builtin = ["system/rust_builtin"]
@@ -0,0 +1,79 @@
use sys::inner::prelude::*;
use sys::os_str::prelude as os_str;
use sys::error::prelude as error;

use ffi::{OsStr, OsString};
use path::{Path, PathBuf};
use io;

struct Conv<T>(T);

impl<T, U> Into<io::Result<U>> for Conv<Result<T, error::Error>> where Conv<T>: Into<U> {
fn into(self) -> io::Result<U> {
self.0.map_err(From::from).map(conv)
}
}

impl Into<io::Error> for Conv<error::Error> {
fn into(self) -> io::Error {
From::from(self.0)
}
}

impl Into<PathBuf> for Conv<os_str::OsString> {
fn into(self) -> PathBuf {
PathBuf::from(OsString::from_inner(self.0))
}
}

impl Into<OsString> for Conv<os_str::OsString> {
fn into(self) -> OsString {
OsString::from_inner(self.0)
}
}

impl<'a> Into<&'a os_str::OsStr> for Conv<&'a OsStr> {
fn into(self) -> &'a os_str::OsStr {
self.0.as_inner()
}
}

impl<'a> Into<&'a os_str::OsStr> for Conv<&'a Path> {
fn into(self) -> &'a os_str::OsStr {
self.0.as_os_str().as_inner()
}
}

impl<'a> Into<&'a OsStr> for Conv<&'a os_str::OsStr> {
fn into(self) -> &'a OsStr {
FromInner::from_inner(self.0)
}
}

impl Into<()> for Conv<()> {
fn into(self) -> () {
self.0
}
}

impl Into<usize> for Conv<usize> {
fn into(self) -> usize {
self.0
}
}

impl Into<u64> for Conv<u64> {
fn into(self) -> u64 {
self.0
}
}

impl<T: AsRef<U>, U> AsRef<U> for Conv<T> {
fn as_ref(&self) -> &U {
self.0.as_ref()
}
}

pub fn conv<T, U>(t: T) -> U where Conv<T>: Into<U> {
Conv(t).into()
}
@@ -19,23 +19,22 @@
#![allow(missing_docs)]

use prelude::v1::*;
use sys::inner::prelude::*;
use sys::dynamic_lib::traits::*;
use sys::dynamic_lib::prelude as sys;

use env;
use ffi::{CString, OsString};
use ffi::OsString;
use mem;
use path::{Path, PathBuf};

pub struct DynamicLibrary {
handle: *mut u8
handle: sys::DynamicLibrary
}

impl Drop for DynamicLibrary {
fn drop(&mut self) {
match dl::check_for_errors_in(|| {
unsafe {
dl::close(self.handle)
}
}) {
match sys::DynamicLibrary::close(&self.handle) {
Ok(()) => {},
Err(str) => panic!("{}", str)
}
@@ -45,8 +44,8 @@ impl Drop for DynamicLibrary {
impl DynamicLibrary {
/// Lazily open a dynamic library. When passed None it gives a
/// handle to the calling process
pub fn open(filename: Option<&Path>) -> Result<DynamicLibrary, String> {
let maybe_library = dl::open(filename.map(|path| path.as_os_str()));
pub fn open(filename: Option<&Path>) -> Result<DynamicLibrary, sys::Error> {
let maybe_library = sys::DynamicLibrary::open(filename.map(Path::as_os_str).map(AsInner::as_inner));

// The dynamic library must not be constructed if there is
// an error opening the library so the destructor does not
@@ -78,17 +77,11 @@ impl DynamicLibrary {
/// Returns the environment variable for this process's dynamic library
/// search path
pub fn envvar() -> &'static str {
if cfg!(windows) {
"PATH"
} else if cfg!(target_os = "macos") {
"DYLD_LIBRARY_PATH"
} else {
"LD_LIBRARY_PATH"
}
sys::DynamicLibrary::envvar()
}

fn separator() -> &'static str {
if cfg!(windows) { ";" } else { ":" }
sys::DynamicLibrary::separator()
}

/// Returns the current search path for dynamic libraries being used by this
@@ -101,14 +94,11 @@ impl DynamicLibrary {
}

/// Accesses the value at the symbol of the dynamic library.
pub unsafe fn symbol<T>(&self, symbol: &str) -> Result<*mut T, String> {
pub unsafe fn symbol<T>(&self, symbol: &str) -> Result<*mut T, sys::Error> {
// This function should have a lifetime constraint of 'a on
// T but that feature is still unimplemented

let raw_string = CString::new(symbol).unwrap();
let maybe_symbol_value = dl::check_for_errors_in(|| {
dl::symbol(self.handle, raw_string.as_ptr())
});
let maybe_symbol_value = sys::DynamicLibrary::symbol(&self.handle, symbol);

// The value must not be constructed if there is an error so
// the destructor does not run.
@@ -123,7 +113,7 @@ impl DynamicLibrary {
mod tests {
use super::*;
use prelude::v1::*;
use libc;
use sys::c::prelude as c;
use mem;
use path::Path;

@@ -139,7 +129,7 @@ mod tests {
Ok(libm) => libm
};

let cosine: extern fn(libc::c_double) -> libc::c_double = unsafe {
let cosine: extern fn(c::c_double) -> c::c_double = unsafe {
match libm.symbol("cos") {
Err(error) => panic!("Could not load function cos: {}", error),
Ok(cosine) => mem::transmute::<*mut u8, _>(cosine)
@@ -173,203 +163,3 @@ mod tests {
}
}
}

#[cfg(any(target_os = "linux",
target_os = "android",
target_os = "macos",
target_os = "ios",
target_os = "freebsd",
target_os = "dragonfly",
target_os = "bitrig",
target_os = "netbsd",
target_os = "openbsd"))]
mod dl {
use prelude::v1::*;

use ffi::{CStr, OsStr};
use str;
use libc;
use ptr;

pub fn open(filename: Option<&OsStr>) -> Result<*mut u8, String> {
check_for_errors_in(|| {
unsafe {
match filename {
Some(filename) => open_external(filename),
None => open_internal(),
}
}
})
}

const LAZY: libc::c_int = 1;

unsafe fn open_external(filename: &OsStr) -> *mut u8 {
let s = filename.to_cstring().unwrap();
dlopen(s.as_ptr(), LAZY) as *mut u8
}

unsafe fn open_internal() -> *mut u8 {
dlopen(ptr::null(), LAZY) as *mut u8
}

pub fn check_for_errors_in<T, F>(f: F) -> Result<T, String> where
F: FnOnce() -> T,
{
use sync::StaticMutex;
static LOCK: StaticMutex = StaticMutex::new();
unsafe {
// dlerror isn't thread safe, so we need to lock around this entire
// sequence
let _guard = LOCK.lock();
let _old_error = dlerror();

let result = f();

let last_error = dlerror() as *const _;
let ret = if ptr::null() == last_error {
Ok(result)
} else {
let s = CStr::from_ptr(last_error).to_bytes();
Err(str::from_utf8(s).unwrap().to_owned())
};

ret
}
}

pub unsafe fn symbol(handle: *mut u8,
symbol: *const libc::c_char) -> *mut u8 {
dlsym(handle as *mut libc::c_void, symbol) as *mut u8
}
pub unsafe fn close(handle: *mut u8) {
dlclose(handle as *mut libc::c_void); ()
}

extern {
fn dlopen(filename: *const libc::c_char,
flag: libc::c_int) -> *mut libc::c_void;
fn dlerror() -> *mut libc::c_char;
fn dlsym(handle: *mut libc::c_void,
symbol: *const libc::c_char) -> *mut libc::c_void;
fn dlclose(handle: *mut libc::c_void) -> libc::c_int;
}
}

#[cfg(target_os = "windows")]
mod dl {
use prelude::v1::*;

use ffi::OsStr;
use libc;
use libc::consts::os::extra::ERROR_CALL_NOT_IMPLEMENTED;
use sys::os;
use os::windows::prelude::*;
use ptr;
use sys::c::SetThreadErrorMode;

pub fn open(filename: Option<&OsStr>) -> Result<*mut u8, String> {
// disable "dll load failed" error dialog.
let mut use_thread_mode = true;
let prev_error_mode = unsafe {
// SEM_FAILCRITICALERRORS 0x01
let new_error_mode = 1;
let mut prev_error_mode = 0;
// Windows >= 7 supports thread error mode.
let result = SetThreadErrorMode(new_error_mode, &mut prev_error_mode);
if result == 0 {
let err = os::errno();
if err as libc::c_int == ERROR_CALL_NOT_IMPLEMENTED {
use_thread_mode = false;
// SetThreadErrorMode not found. use fallback solution:
// SetErrorMode() Note that SetErrorMode is process-wide so
// this can cause race condition! However, since even
// Windows APIs do not care of such problem (#20650), we
// just assume SetErrorMode race is not a great deal.
prev_error_mode = SetErrorMode(new_error_mode);
}
}
prev_error_mode
};

unsafe {
SetLastError(0);
}

let result = match filename {
Some(filename) => {
let filename_str: Vec<_> =
filename.encode_wide().chain(Some(0)).collect();
let result = unsafe {
LoadLibraryW(filename_str.as_ptr() as *const libc::c_void)
};
// beware: Vec/String may change errno during drop!
// so we get error here.
if result == ptr::null_mut() {
let errno = os::errno();
Err(os::error_string(errno))
} else {
Ok(result as *mut u8)
}
}
None => {
let mut handle = ptr::null_mut();
let succeeded = unsafe {
GetModuleHandleExW(0 as libc::DWORD, ptr::null(), &mut handle)
};
if succeeded == libc::FALSE {
let errno = os::errno();
Err(os::error_string(errno))
} else {
Ok(handle as *mut u8)
}
}
};

unsafe {
if use_thread_mode {
SetThreadErrorMode(prev_error_mode, ptr::null_mut());
} else {
SetErrorMode(prev_error_mode);
}
}

result
}

pub fn check_for_errors_in<T, F>(f: F) -> Result<T, String> where
F: FnOnce() -> T,
{
unsafe {
SetLastError(0);

let result = f();

let error = os::errno();
if 0 == error {
Ok(result)
} else {
Err(format!("Error code {}", error))
}
}
}

pub unsafe fn symbol(handle: *mut u8, symbol: *const libc::c_char) -> *mut u8 {
GetProcAddress(handle as *mut libc::c_void, symbol) as *mut u8
}
pub unsafe fn close(handle: *mut u8) {
FreeLibrary(handle as *mut libc::c_void); ()
}

#[allow(non_snake_case)]
extern "system" {
fn SetLastError(error: libc::size_t);
fn LoadLibraryW(name: *const libc::c_void) -> *mut libc::c_void;
fn GetModuleHandleExW(dwFlags: libc::DWORD, name: *const u16,
handle: *mut *mut libc::c_void) -> libc::BOOL;
fn GetProcAddress(handle: *mut libc::c_void,
name: *const libc::c_char) -> *mut libc::c_void;
fn FreeLibrary(handle: *mut libc::c_void);
fn SetErrorMode(uMode: libc::c_uint) -> libc::c_uint;
}
}

Large diffs are not rendered by default.

Oops, something went wrong.
@@ -8,6 +8,8 @@
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use sys::c::prelude::*;
use os::raw as libc;
use ascii;
use borrow::{Cow, ToOwned, Borrow};
use boxed::Box;
@@ -17,7 +19,6 @@ use error::Error;
use fmt::{self, Write};
use io;
use iter::Iterator;
use libc;
use mem;
use ops::Deref;
use option::Option::{self, Some, None};
@@ -222,7 +223,7 @@ impl CString {
/// using the pointer.
#[stable(feature = "cstr_memory", since = "1.4.0")]
pub unsafe fn from_raw(ptr: *mut libc::c_char) -> CString {
let len = libc::strlen(ptr) + 1; // Including the NUL byte
let len = strlen(ptr) + 1; // Including the NUL byte
let slice = slice::from_raw_parts(ptr, len as usize);
CString { inner: mem::transmute(slice) }
}
@@ -376,7 +377,7 @@ impl CStr {
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub unsafe fn from_ptr<'a>(ptr: *const libc::c_char) -> &'a CStr {
let len = libc::strlen(ptr);
let len = strlen(ptr);
mem::transmute(slice::from_raw_parts(ptr, len as usize + 1))
}

@@ -489,8 +490,8 @@ impl ToOwned for CStr {
#[cfg(test)]
mod tests {
use prelude::v1::*;
use sys::c::prelude as libc;
use super::*;
use libc;
use borrow::Cow::{Borrowed, Owned};
use hash::{SipHasher, Hash, Hasher};

@@ -29,6 +29,10 @@
//! for conversion to/from various other string types. Eventually these types
//! will offer a full-fledged string API.

use sys::os_str::prelude::{OsString as Buf, OsStr as Slice};
use sys::os_str::traits::*;
use sys::inner::prelude::*;

use borrow::{Borrow, Cow, ToOwned};
use ffi::CString;
use fmt::{self, Debug};
@@ -39,9 +43,6 @@ use cmp;
use hash::{Hash, Hasher};
use vec::Vec;

use sys::os_str::{Buf, Slice};
use sys_common::{AsInner, IntoInner, FromInner};

/// Owned, mutable OS strings.
#[derive(Clone)]
#[stable(feature = "rust1", since = "1.0.0")]
@@ -73,18 +74,7 @@ impl OsString {
/// convert; non UTF-8 data will produce `None`.
#[unstable(feature = "convert", reason = "recently added", issue = "27704")]
pub fn from_bytes<B>(bytes: B) -> Option<OsString> where B: Into<Vec<u8>> {
Self::_from_bytes(bytes.into())
}

#[cfg(unix)]
fn _from_bytes(vec: Vec<u8>) -> Option<OsString> {
use os::unix::ffi::OsStringExt;
Some(OsString::from_vec(vec))
}

#[cfg(windows)]
fn _from_bytes(vec: Vec<u8>) -> Option<OsString> {
String::from_utf8(vec).ok().map(OsString::from)
Buf::from_bytes(bytes.into()).map(FromInner::from_inner)
}

/// Converts to an `OsStr` slice.
@@ -128,7 +118,7 @@ impl ops::Index<ops::RangeFull> for OsString {

#[inline]
fn index(&self, _index: ops::RangeFull) -> &OsStr {
OsStr::from_inner(self.inner.as_slice())
FromInner::from_inner(self.inner.borrow())
}
}

@@ -220,10 +210,6 @@ impl OsStr {
s.as_ref()
}

fn from_inner(inner: &Slice) -> &OsStr {
unsafe { mem::transmute(inner) }
}

/// Yields a `&str` slice if the `OsStr` is valid unicode.
///
/// This conversion may entail doing a check for UTF-8 validity.
@@ -257,11 +243,7 @@ impl OsStr {
/// data. This may entail checking validity.
#[unstable(feature = "convert", reason = "recently added", issue = "27704")]
pub fn to_bytes(&self) -> Option<&[u8]> {
if cfg!(windows) {
self.to_str().map(|s| s.as_bytes())
} else {
Some(self.bytes())
}
self.inner.to_bytes()
}

/// Creates a `CString` containing this `OsStr` data.
@@ -385,7 +367,7 @@ impl AsRef<OsStr> for OsString {
#[stable(feature = "rust1", since = "1.0.0")]
impl AsRef<OsStr> for str {
fn as_ref(&self) -> &OsStr {
OsStr::from_inner(Slice::from_str(self))
FromInner::from_inner(Slice::from_str(self))
}
}

@@ -408,6 +390,12 @@ impl IntoInner<Buf> for OsString {
}
}

impl<'a> FromInner<&'a Slice> for &'a OsStr {
fn from_inner(inner: &Slice) -> Self {
unsafe { mem::transmute(inner) }
}
}

impl AsInner<Slice> for OsStr {
fn as_inner(&self) -> &Slice {
&self.inner

Large diffs are not rendered by default.

Oops, something went wrong.
@@ -8,14 +8,18 @@
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use sys::inner::prelude::*;
use sys::error::traits::*;
use sys::error::prelude as sys;
use sys::c::prelude as c;

use boxed::Box;
use convert::Into;
use error;
use fmt;
use marker::{Send, Sync};
use option::Option::{self, Some, None};
use result;
use sys;

/// A specialized [`Result`][result] type for I/O operations.
///
@@ -64,7 +68,7 @@ pub struct Error {
}

enum Repr {
Os(i32),
Os(sys::Error),
Custom(Box<Custom>),
}

@@ -210,13 +214,13 @@ impl Error {
/// `Error` for the error code.
#[stable(feature = "rust1", since = "1.0.0")]
pub fn last_os_error() -> Error {
Error::from_raw_os_error(sys::os::errno() as i32)
Error::from(sys::Error::expect_last_error())
}

/// Creates a new instance of an `Error` from a particular OS error code.
#[stable(feature = "rust1", since = "1.0.0")]
pub fn from_raw_os_error(code: i32) -> Error {
Error { repr: Repr::Os(code) }
Error::from(sys::Error::from_code(code))
}

/// Returns the OS error that this error represents (if any).
@@ -227,7 +231,7 @@ impl Error {
#[stable(feature = "rust1", since = "1.0.0")]
pub fn raw_os_error(&self) -> Option<i32> {
match self.repr {
Repr::Os(i) => Some(i),
Repr::Os(ref i) => Some(i.code()),
Repr::Custom(..) => None,
}
}
@@ -273,7 +277,7 @@ impl Error {
#[stable(feature = "rust1", since = "1.0.0")]
pub fn kind(&self) -> ErrorKind {
match self.repr {
Repr::Os(code) => sys::decode_error_kind(code),
Repr::Os(ref e) => decode_error_kind(e),
Repr::Custom(ref c) => c.kind,
}
}
@@ -282,9 +286,9 @@ impl Error {
impl fmt::Debug for Repr {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
match *self {
Repr::Os(ref code) =>
fmt.debug_struct("Os").field("code", code)
.field("message", &sys::os::error_string(*code)).finish(),
Repr::Os(ref e) =>
fmt.debug_struct("Os").field("code", &e.code())
.field("message", &e.description().to_string_lossy()).finish(),
Repr::Custom(ref c) => fmt.debug_tuple("Custom").field(c).finish(),
}
}
@@ -294,9 +298,9 @@ impl fmt::Debug for Repr {
impl fmt::Display for Error {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
match self.repr {
Repr::Os(code) => {
let detail = sys::os::error_string(code);
write!(fmt, "{} (os error {})", detail, code)
Repr::Os(ref e) => {
let detail = e.description();
write!(fmt, "{} (os error {})", detail.to_string_lossy(), e.code())
}
Repr::Custom(ref c) => c.error.fmt(fmt),
}
@@ -320,6 +324,22 @@ impl error::Error for Error {
}
}

impl From<sys::Error> for Error {
fn from(e: sys::Error) -> Self {
Error { repr: Repr::Os(e) }
}
}

impl IntoInner<sys::Error> for Error {
fn into_inner(self) -> sys::Error {
sys::Error::from_code(self.raw_os_error().unwrap_or(c::EIO))
}
}

fn decode_error_kind(err: &sys::Error) -> ErrorKind {
unimplemented!()
}

fn _assert_error_is_sync_send() {
fn _is_sync_send<T: Sync+Send>() {}
_is_sync_send::<Error>();
@@ -328,17 +348,19 @@ fn _assert_error_is_sync_send() {
#[cfg(test)]
mod test {
use prelude::v1::*;
use sys::error::traits::*;
use sys::error::prelude as sys;
use super::{Error, ErrorKind};
use error;
use error::Error as error_Error;
use fmt;
use sys::os::error_string;

#[test]
fn test_debug_error() {
let code = 6;
let msg = error_string(code);
let err = Error { repr: super::Repr::Os(code) };
let msg = sys::Error::from_code(code).description();
let msg = msg.to_str().unwrap();
let err = Error { repr: super::Repr::Os(sys::Error::from_code(code)) };
let expected = format!("Error {{ repr: Os {{ code: {:?}, message: {:?} }} }}", code, msg);
assert_eq!(format!("{:?}", err), expected);
}
@@ -12,8 +12,8 @@ use prelude::v1::*;

use cell::Cell;
use ptr;
use util;
use sync::{StaticMutex, Arc};
use sys_common;

pub struct Lazy<T> {
lock: StaticMutex,
@@ -51,7 +51,7 @@ impl<T: Send + Sync + 'static> Lazy<T> {
// `Arc` allocation in our own internal box (it will get deallocated by
// the at exit handler). Otherwise we just return the freshly allocated
// `Arc`.
let registered = sys_common::at_exit(move || {
let registered = util::at_exit(move || {
let g = self.lock.lock();
let ptr = self.ptr.get();
self.ptr.set(1 as *mut _);
@@ -241,6 +241,9 @@

#![stable(feature = "rust1", since = "1.0.0")]

use sys::inner::prelude::*;
use sys::io::prelude as sys;

use cmp;
use rustc_unicode::str as core_str;
use error as std_error;
@@ -264,6 +267,7 @@ pub use self::stdio::{stdin, stdout, stderr, _print, Stdin, Stdout, Stderr};
pub use self::stdio::{StdoutLock, StderrLock, StdinLock};
#[doc(no_inline, hidden)]
pub use self::stdio::{set_panic, set_print};
pub use self::read_uninitialized::read_to_end_uninitialized;

pub mod prelude;
mod buffered;
@@ -273,6 +277,7 @@ mod impls;
mod lazy;
mod util;
mod stdio;
mod read_uninitialized;

const DEFAULT_BUF_SIZE: usize = 64 * 1024;

@@ -1169,6 +1174,16 @@ pub enum SeekFrom {
Current(i64),
}

impl IntoInner<sys::SeekFrom> for SeekFrom {
fn into_inner(self) -> sys::SeekFrom {
match self {
SeekFrom::Start(v) => sys::SeekFrom::Start(v),
SeekFrom::End(v) => sys::SeekFrom::End(v),
SeekFrom::Current(v) => sys::SeekFrom::Current(v),
}
}
}

fn read_until<R: BufRead + ?Sized>(r: &mut R, delim: u8, buf: &mut Vec<u8>)
-> Result<usize> {
let mut read = 0;
@@ -13,16 +13,17 @@ use io::ErrorKind;
use io::Read;
use slice::from_raw_parts_mut;

// Provides read_to_end functionality over an uninitialized buffer.
// This function is unsafe because it calls the underlying
// read function with a slice into uninitialized memory. The default
// implementation of read_to_end for readers will zero out new memory in
// the buf before passing it to read, but avoiding this zero can often
// lead to a fairly significant performance win.
//
// Implementations using this method have to adhere to two guarantees:
// * The implementation of read never reads the buffer provided.
// * The implementation of read correctly reports how many bytes were written.
/// Provides read_to_end functionality over an uninitialized buffer.
/// This function is unsafe because it calls the underlying
/// read function with a slice into uninitialized memory. The default
/// implementation of read_to_end for readers will zero out new memory in
/// the buf before passing it to read, but avoiding this zero can often
/// lead to a fairly significant performance win.
///
/// Implementations using this method have to adhere to two guarantees:
/// * The implementation of read never reads the buffer provided.
/// * The implementation of read correctly reports how many bytes were written.
#[unstable(feature = "read_to_end_uninitialized", reason = "unsure", issue = "0")]
pub unsafe fn read_to_end_uninitialized(r: &mut Read, buf: &mut Vec<u8>) -> io::Result<usize> {

let start_len = buf.len();
@@ -11,16 +11,18 @@
use prelude::v1::*;
use io::prelude::*;

use sys::io::traits::*;
use sys::stdio::traits::*;
use sys::stdio::prelude as sys;
use sys::io::prelude as sys_io;

use cell::{RefCell, BorrowState};
use cmp;
use fmt;
use io::lazy::Lazy;
use io::{self, BufReader, LineWriter};
use io::{self, BufReader, LineWriter, read_to_end_uninitialized};
use sync::{Arc, Mutex, MutexGuard};
use sys::stdio;
use sys_common::io::{read_to_end_uninitialized};
use sys_common::remutex::{ReentrantMutex, ReentrantMutexGuard};
use libc;
use sync::{ReentrantMutex, ReentrantMutexGuard};

/// Stdout used by print! and println! macros
thread_local! {
@@ -33,19 +35,19 @@ thread_local! {
///
/// This handle is not synchronized or buffered in any fashion. Constructed via
/// the `std::io::stdio::stdin_raw` function.
struct StdinRaw(stdio::Stdin);
type StdinRaw = sys::Stdin;

/// A handle to a raw instance of the standard output stream of this process.
///
/// This handle is not synchronized or buffered in any fashion. Constructed via
/// the `std::io::stdio::stdout_raw` function.
struct StdoutRaw(stdio::Stdout);
type StdoutRaw = sys::Stdout;

/// A handle to a raw instance of the standard output stream of this process.
///
/// This handle is not synchronized or buffered in any fashion. Constructed via
/// the `std::io::stdio::stderr_raw` function.
struct StderrRaw(stdio::Stderr);
type StderrRaw = sys::Stderr;

/// Constructs a new raw handle to the standard input of this process.
///
@@ -54,7 +56,7 @@ struct StderrRaw(stdio::Stderr);
/// handles is **not** available to raw handles returned from this function.
///
/// The returned handle has no external synchronization or buffering.
fn stdin_raw() -> io::Result<StdinRaw> { stdio::Stdin::new().map(StdinRaw) }
fn stdin_raw() -> io::Result<StdinRaw> { sys::Stdio::stdin().map_err(From::from) }

/// Constructs a new raw handle to the standard output stream of this process.
///
@@ -65,7 +67,7 @@ fn stdin_raw() -> io::Result<StdinRaw> { stdio::Stdin::new().map(StdinRaw) }
///
/// The returned handle has no external synchronization or buffering layered on
/// top.
fn stdout_raw() -> io::Result<StdoutRaw> { stdio::Stdout::new().map(StdoutRaw) }
fn stdout_raw() -> io::Result<StdoutRaw> { sys::Stdio::stdout().map_err(From::from) }

/// Constructs a new raw handle to the standard error stream of this process.
///
@@ -74,62 +76,38 @@ fn stdout_raw() -> io::Result<StdoutRaw> { stdio::Stdout::new().map(StdoutRaw) }
///
/// The returned handle has no external synchronization or buffering layered on
/// top.
fn stderr_raw() -> io::Result<StderrRaw> { stdio::Stderr::new().map(StderrRaw) }

impl Read for StdinRaw {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { self.0.read(buf) }
}
impl Write for StdoutRaw {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.0.write(buf) }
fn flush(&mut self) -> io::Result<()> { Ok(()) }
}
impl Write for StderrRaw {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.0.write(buf) }
fn flush(&mut self) -> io::Result<()> { Ok(()) }
}
fn stderr_raw() -> io::Result<StderrRaw> { sys::Stdio::stderr().map_err(From::from) }

enum Maybe<T> {
Real(T),
Fake,
}

impl<W: io::Write> io::Write for Maybe<W> {
impl<W: sys_io::Write> io::Write for Maybe<W> {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
match *self {
Maybe::Real(ref mut w) => handle_ebadf(w.write(buf), buf.len()),
Maybe::Real(ref mut w) => sys::handle_ebadf::<sys::Stdio, _>(w.write(buf), buf.len()).map_err(From::from),
Maybe::Fake => Ok(buf.len())
}
}

fn flush(&mut self) -> io::Result<()> {
match *self {
Maybe::Real(ref mut w) => handle_ebadf(w.flush(), ()),
Maybe::Real(ref mut w) => sys::handle_ebadf::<sys::Stdio, _>(w.flush(), ()).map_err(From::from),
Maybe::Fake => Ok(())
}
}
}

impl<R: io::Read> io::Read for Maybe<R> {
impl<R: sys_io::Read> io::Read for Maybe<R> {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
match *self {
Maybe::Real(ref mut r) => handle_ebadf(r.read(buf), buf.len()),
Maybe::Real(ref mut r) => sys::handle_ebadf::<sys::Stdio, _>(r.read(buf), buf.len()).map_err(From::from),
Maybe::Fake => Ok(0)
}
}
}

fn handle_ebadf<T>(r: io::Result<T>, default: T) -> io::Result<T> {
#[cfg(windows)]
const ERR: libc::c_int = libc::ERROR_INVALID_HANDLE;
#[cfg(not(windows))]
const ERR: libc::c_int = libc::EBADF;

match r {
Err(ref e) if e.raw_os_error() == Some(ERR) => Ok(default),
r => r
}
}

/// A handle to the standard input stream of a process.
///
/// Each handle is a shared reference to a global buffer of input data to this
@@ -305,7 +283,7 @@ impl<'a> BufRead for StdinLock<'a> {
// [2]: http://www.mail-archive.com/log4net-dev@logging.apache.org/msg00661.html
#[cfg(windows)]
const OUT_MAX: usize = 8192;
#[cfg(unix)]
#[cfg(not(windows))]
const OUT_MAX: usize = ::usize::MAX;

/// A handle to the global standard output stream of the current process.
@@ -538,8 +516,9 @@ impl<'a> Write for StderrLock<'a> {
issue = "0")]
#[doc(hidden)]
pub fn set_panic(sink: Box<Write + Send>) -> Option<Box<Write + Send>> {
use panicking::LOCAL_STDERR;
use util::LOCAL_STDERR;
use mem;

LOCAL_STDERR.with(move |slot| {
mem::replace(&mut *slot.borrow_mut(), Some(sink))
}).and_then(|mut s| {
@@ -222,7 +222,6 @@
#![feature(into_cow)]
#![feature(iter_order)]
#![feature(lang_items)]
#![feature(libc)]
#![feature(linkage, thread_local, asm)]
#![feature(macro_reexport)]
#![feature(slice_concat_ext)]
@@ -238,6 +237,7 @@
#![feature(staged_api)]
#![feature(str_char)]
#![feature(str_internals)]
#![feature(system)]
#![feature(unboxed_closures)]
#![feature(unicode)]
#![feature(unique)]
@@ -248,6 +248,7 @@
#![feature(vec_resize)]
#![feature(wrapping)]
#![feature(zero_one)]
#![cfg_attr(any(windows, unix), feature(libc))]
#![cfg_attr(windows, feature(str_utf16))]
#![cfg_attr(test, feature(float_from_str_radix, range_inclusive, float_extras))]
#![cfg_attr(test, feature(test, rustc_private))]
@@ -275,7 +276,6 @@ extern crate collections as core_collections;
#[allow(deprecated)] extern crate rand as core_rand;
extern crate alloc;
extern crate rustc_unicode;
extern crate libc;

// Make std testable by not duplicating lang items and other globals. See #2912
#[cfg(test)] extern crate std as realstd;
@@ -319,7 +319,7 @@ pub use rustc_unicode::char;
#[macro_use]
mod macros;

mod rtdeps;
//mod rtdeps;

/* The Prelude. */

@@ -344,8 +344,8 @@ pub use core::u16;
pub use core::u32;
pub use core::u64;

#[path = "num/f32.rs"] pub mod f32;
#[path = "num/f64.rs"] pub mod f64;
#[path = "num/f32.rs"] pub mod f32;
#[path = "num/f64.rs"] pub mod f64;

pub mod ascii;

@@ -358,29 +358,33 @@ pub mod num;
#[macro_use]
pub mod thread;

mod conv;

#[path = "rt/mod.rs"] mod util;

extern crate system as sys;

/// OS-specific functionality
#[stable(feature = "os", since = "1.0.0")]
pub mod os {
pub use sys::os::*;

#[cfg(unix)] pub mod unix;
#[cfg(windows)] pub mod windows;
}

pub mod collections;
pub mod dynamic_lib;
pub mod env;
pub mod ffi;
pub mod fs;
pub mod io;
pub mod net;
pub mod os;
pub mod path;
pub mod process;
pub mod sync;
pub mod time;

#[macro_use]
#[path = "sys/common/mod.rs"] mod sys_common;

#[cfg(unix)]
#[path = "sys/unix/mod.rs"] mod sys;
#[cfg(windows)]
#[path = "sys/windows/mod.rs"] mod sys;

pub mod rt;
mod panicking;
mod rand;

// Some external utilities of the standard library rely on randomness (aka
@@ -394,6 +398,30 @@ pub mod __rand {
pub use rand::{thread_rng, ThreadRng, Rng};
}

// Reexport some of our utilities which are expected by other crates.
#[doc(hidden)]
#[unstable(feature = "rt",
reason = "this public module should not exist and is highly likely \
to disappear",
issue = "0")]
pub mod rt {
use sys::unwind::prelude::*;
use fmt;
use any::Any;

#[inline(always)]
pub fn begin_unwind_fmt(msg: fmt::Arguments, file_line: &(&'static str, u32)) -> ! {
Unwind::begin_unwind_fmt(msg, file_line)
}

#[inline(always)]
pub fn begin_unwind<M: Any + Send>(msg: M, file_line: &(&'static str, u32)) -> ! {
Unwind::begin_unwind(msg, file_line)
}

pub use util::rust_std_on_panic;
}

// Include a number of private modules that exist solely to provide
// the rustdoc documentation for primitive types. Using `include!`
// because rustdoc only looks for these modules at the crate level.
@@ -9,15 +9,15 @@
// except according to those terms.

use prelude::v1::*;
use sys::inner::prelude::*;
use sys::net::traits::*;
use sys::net::prelude as sys;

use fmt;
use hash;
use io;
use libc::{self, socklen_t, sa_family_t};
use mem;
use net::{lookup_host, ntoh, hton, IpAddr, Ipv4Addr, Ipv6Addr};
use net::{lookup_host, IpAddr, Ipv4Addr, Ipv6Addr};
use option;
use sys_common::{FromInner, AsInner, IntoInner};
use vec;

/// Representation of a socket address for networking applications.
@@ -39,12 +39,12 @@ pub enum SocketAddr {
/// An IPv4 socket address which is a (ip, port) combination.
#[derive(Copy)]
#[stable(feature = "rust1", since = "1.0.0")]
pub struct SocketAddrV4 { inner: libc::sockaddr_in }
pub struct SocketAddrV4 { inner: sys::SocketAddrV4 }

/// An IPv6 socket address.
#[derive(Copy)]
#[stable(feature = "rust1", since = "1.0.0")]
pub struct SocketAddrV6 { inner: libc::sockaddr_in6 }
pub struct SocketAddrV6 { inner: sys::SocketAddrV6 }

impl SocketAddr {
/// Creates a new socket address from the (ip, port) pair.
@@ -80,26 +80,17 @@ impl SocketAddrV4 {
#[stable(feature = "rust1", since = "1.0.0")]
pub fn new(ip: Ipv4Addr, port: u16) -> SocketAddrV4 {
SocketAddrV4 {
inner: libc::sockaddr_in {
sin_family: libc::AF_INET as sa_family_t,
sin_port: hton(port),
sin_addr: *ip.as_inner(),
.. unsafe { mem::zeroed() }
},
inner: sys::SocketAddrV4::new(*ip.as_inner(), port),
}
}

/// Returns the IP address associated with this socket address.
#[stable(feature = "rust1", since = "1.0.0")]
pub fn ip(&self) -> &Ipv4Addr {
unsafe {
&*(&self.inner.sin_addr as *const libc::in_addr as *const Ipv4Addr)
}
}
pub fn ip(&self) -> &Ipv4Addr { FromInner::from_inner(self.inner.addr()) }

/// Returns the port number associated with this socket address.
#[stable(feature = "rust1", since = "1.0.0")]
pub fn port(&self) -> u16 { ntoh(self.inner.sin_port) }
pub fn port(&self) -> u16 { self.inner.port() }
}

impl SocketAddrV6 {
@@ -109,65 +100,71 @@ impl SocketAddrV6 {
pub fn new(ip: Ipv6Addr, port: u16, flowinfo: u32, scope_id: u32)
-> SocketAddrV6 {
SocketAddrV6 {
inner: libc::sockaddr_in6 {
sin6_family: libc::AF_INET6 as sa_family_t,
sin6_port: hton(port),
sin6_addr: *ip.as_inner(),
sin6_flowinfo: hton(flowinfo),
sin6_scope_id: hton(scope_id),
.. unsafe { mem::zeroed() }
},
inner: sys::SocketAddrV6::new(*ip.as_inner(), port, flowinfo, scope_id),
}
}

/// Returns the IP address associated with this socket address.
#[stable(feature = "rust1", since = "1.0.0")]
pub fn ip(&self) -> &Ipv6Addr {
unsafe {
&*(&self.inner.sin6_addr as *const libc::in6_addr as *const Ipv6Addr)
}
}
pub fn ip(&self) -> &Ipv6Addr { FromInner::from_inner(self.inner.addr()) }

/// Returns the port number associated with this socket address.
#[stable(feature = "rust1", since = "1.0.0")]
pub fn port(&self) -> u16 { ntoh(self.inner.sin6_port) }
pub fn port(&self) -> u16 { self.inner.port() }

/// Returns scope ID associated with this address, corresponding to the
/// `sin6_flowinfo` field in C.
#[stable(feature = "rust1", since = "1.0.0")]
pub fn flowinfo(&self) -> u32 { ntoh(self.inner.sin6_flowinfo) }
pub fn flowinfo(&self) -> u32 { self.inner.flowinfo() }

/// Returns scope ID associated with this address, corresponding to the
/// `sin6_scope_id` field in C.
#[stable(feature = "rust1", since = "1.0.0")]
pub fn scope_id(&self) -> u32 { ntoh(self.inner.sin6_scope_id) }
pub fn scope_id(&self) -> u32 { self.inner.scope_id() }
}

impl FromInner<libc::sockaddr_in> for SocketAddrV4 {
fn from_inner(addr: libc::sockaddr_in) -> SocketAddrV4 {
impl FromInner<sys::SocketAddrV4> for SocketAddrV4 {
fn from_inner(addr: sys::SocketAddrV4) -> SocketAddrV4 {
SocketAddrV4 { inner: addr }
}
}

impl FromInner<libc::sockaddr_in6> for SocketAddrV6 {
fn from_inner(addr: libc::sockaddr_in6) -> SocketAddrV6 {
impl FromInner<sys::SocketAddrV6> for SocketAddrV6 {
fn from_inner(addr: sys::SocketAddrV6) -> SocketAddrV6 {
SocketAddrV6 { inner: addr }
}
}

impl<'a> IntoInner<(*const libc::sockaddr, socklen_t)> for &'a SocketAddr {
fn into_inner(self) -> (*const libc::sockaddr, socklen_t) {
impl FromInner<sys::SocketAddr> for SocketAddr {
fn from_inner(addr: sys::SocketAddr) -> SocketAddr {
match addr {
sys::socketaddr::V4(addr) => SocketAddr::V4(FromInner::from_inner(addr)),
sys::socketaddr::V6(addr) => SocketAddr::V6(FromInner::from_inner(addr)),
}
}
}

impl<'a> IntoInner<sys::SocketAddr> for &'a SocketAddr {
fn into_inner(self) -> sys::SocketAddr {
match *self {
SocketAddr::V4(ref a) => {
(a as *const _ as *const _, mem::size_of_val(a) as socklen_t)
}
SocketAddr::V6(ref a) => {
(a as *const _ as *const _, mem::size_of_val(a) as socklen_t)
}
SocketAddr::V4(ref addr) => sys::socketaddr::V4(*addr.as_inner()),
SocketAddr::V6(ref addr) => sys::socketaddr::V6(*addr.as_inner()),
}
}
}

impl AsInner<sys::SocketAddrV4> for SocketAddrV4 {
fn as_inner(&self) -> &sys::SocketAddrV4 {
&self.inner
}
}

impl AsInner<sys::SocketAddrV6> for SocketAddrV6 {
fn as_inner(&self) -> &sys::SocketAddrV6 {
&self.inner
}
}

#[stable(feature = "rust1", since = "1.0.0")]
impl fmt::Display for SocketAddr {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
@@ -218,17 +215,13 @@ impl Clone for SocketAddrV6 {
#[stable(feature = "rust1", since = "1.0.0")]
impl PartialEq for SocketAddrV4 {
fn eq(&self, other: &SocketAddrV4) -> bool {
self.inner.sin_port == other.inner.sin_port &&
self.inner.sin_addr.s_addr == other.inner.sin_addr.s_addr
self.inner == other.inner
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl PartialEq for SocketAddrV6 {
fn eq(&self, other: &SocketAddrV6) -> bool {
self.inner.sin6_port == other.inner.sin6_port &&
self.inner.sin6_addr.s6_addr == other.inner.sin6_addr.s6_addr &&
self.inner.sin6_flowinfo == other.inner.sin6_flowinfo &&
self.inner.sin6_scope_id == other.inner.sin6_scope_id
self.inner == other.inner
}
}
#[stable(feature = "rust1", since = "1.0.0")]
@@ -239,14 +232,13 @@ impl Eq for SocketAddrV6 {}
#[stable(feature = "rust1", since = "1.0.0")]
impl hash::Hash for SocketAddrV4 {
fn hash<H: hash::Hasher>(&self, s: &mut H) {
(self.inner.sin_port, self.inner.sin_addr.s_addr).hash(s)
self.inner.hash(s)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl hash::Hash for SocketAddrV6 {
fn hash<H: hash::Hasher>(&self, s: &mut H) {
(self.inner.sin6_port, &self.inner.sin6_addr.s6_addr,
self.inner.sin6_flowinfo, self.inner.sin6_scope_id).hash(s)
self.inner.hash(s)
}
}

@@ -14,13 +14,14 @@
issue = "27709")]

use prelude::v1::*;
use sys::inner::prelude::*;
use sys::net::traits::*;
use sys::net::prelude as sys;

use cmp::Ordering;
use hash;
use fmt;
use libc;
use sys_common::{AsInner, FromInner};
use net::{hton, ntoh};
use mem;

/// An IP address, either an IPv4 or IPv6 address.
#[unstable(feature = "ip_addr", reason = "recent addition", issue = "27801")]
@@ -36,14 +37,14 @@ pub enum IpAddr {
#[derive(Copy)]
#[stable(feature = "rust1", since = "1.0.0")]
pub struct Ipv4Addr {
inner: libc::in_addr,
inner: sys::AddrV4,
}

/// Representation of an IPv6 address.
#[derive(Copy)]
#[stable(feature = "rust1", since = "1.0.0")]
pub struct Ipv6Addr {
inner: libc::in6_addr,
inner: sys::AddrV6,
}

#[allow(missing_docs)]
@@ -58,32 +59,35 @@ pub enum Ipv6MulticastScope {
Global
}

impl IntoInner<sys::IpAddr> for IpAddr {
fn into_inner(self) -> sys::IpAddr {
match self {
IpAddr::V4(addr) => sys::ipaddr::V4(*addr.as_inner()),
IpAddr::V6(addr) => sys::ipaddr::V6(*addr.as_inner()),
}
}
}

impl Ipv4Addr {
/// Creates a new IPv4 address from four eight-bit octets.
///
/// The result will represent the IP address `a`.`b`.`c`.`d`.
#[stable(feature = "rust1", since = "1.0.0")]
pub fn new(a: u8, b: u8, c: u8, d: u8) -> Ipv4Addr {
Ipv4Addr {
inner: libc::in_addr {
s_addr: hton(((a as u32) << 24) |
((b as u32) << 16) |
((c as u32) << 8) |
(d as u32)),
}
inner: sys::AddrV4::new(a, b, c, d),
}
}

/// Returns the four eight-bit integers that make up this address.
#[stable(feature = "rust1", since = "1.0.0")]
pub fn octets(&self) -> [u8; 4] {
let bits = ntoh(self.inner.s_addr);
[(bits >> 24) as u8, (bits >> 16) as u8, (bits >> 8) as u8, bits as u8]
self.inner.octets()
}

/// Returns true for the special 'unspecified' address 0.0.0.0.
pub fn is_unspecified(&self) -> bool {
self.inner.s_addr == 0
self.octets() == [0; 4]
}

/// Returns true if this is a loopback address (127.0.0.0/8).
@@ -211,7 +215,7 @@ impl Clone for Ipv4Addr {
#[stable(feature = "rust1", since = "1.0.0")]
impl PartialEq for Ipv4Addr {
fn eq(&self, other: &Ipv4Addr) -> bool {
self.inner.s_addr == other.inner.s_addr
self.inner == other.inner
}
}

@@ -221,7 +225,7 @@ impl Eq for Ipv4Addr {}
#[stable(feature = "rust1", since = "1.0.0")]
impl hash::Hash for Ipv4Addr {
fn hash<H: hash::Hasher>(&self, s: &mut H) {
self.inner.s_addr.hash(s)
self.inner.hash(s)
}
}

@@ -235,19 +239,26 @@ impl PartialOrd for Ipv4Addr {
#[stable(feature = "rust1", since = "1.0.0")]
impl Ord for Ipv4Addr {
fn cmp(&self, other: &Ipv4Addr) -> Ordering {
self.inner.s_addr.cmp(&other.inner.s_addr)
self.inner.cmp(&other.inner)
}
}

impl AsInner<libc::in_addr> for Ipv4Addr {
fn as_inner(&self) -> &libc::in_addr { &self.inner }
impl AsInner<sys::AddrV4> for Ipv4Addr {
fn as_inner(&self) -> &sys::AddrV4 { &self.inner }
}
impl FromInner<libc::in_addr> for Ipv4Addr {
fn from_inner(addr: libc::in_addr) -> Ipv4Addr {

impl FromInner<sys::AddrV4> for Ipv4Addr {
fn from_inner(addr: sys::AddrV4) -> Ipv4Addr {
Ipv4Addr { inner: addr }
}
}

impl<'a> FromInner<&'a sys::AddrV4> for &'a Ipv4Addr {
fn from_inner(addr: &'a sys::AddrV4) -> &'a Ipv4Addr {
unsafe { mem::transmute(addr) }
}
}

#[stable(feature = "ip_u32", since = "1.1.0")]
impl From<Ipv4Addr> for u32 {
fn from(ip: Ipv4Addr) -> u32 {
@@ -271,24 +282,14 @@ impl Ipv6Addr {
pub fn new(a: u16, b: u16, c: u16, d: u16, e: u16, f: u16, g: u16,
h: u16) -> Ipv6Addr {
Ipv6Addr {
inner: libc::in6_addr {
s6_addr: [hton(a), hton(b), hton(c), hton(d),
hton(e), hton(f), hton(g), hton(h)]
}
inner: sys::AddrV6::new(a, b, c, d, e, f, g, h),
}
}

/// Returns the eight 16-bit segments that make up this address.
#[stable(feature = "rust1", since = "1.0.0")]
pub fn segments(&self) -> [u16; 8] {
[ntoh(self.inner.s6_addr[0]),
ntoh(self.inner.s6_addr[1]),
ntoh(self.inner.s6_addr[2]),
ntoh(self.inner.s6_addr[3]),
ntoh(self.inner.s6_addr[4]),
ntoh(self.inner.s6_addr[5]),
ntoh(self.inner.s6_addr[6]),
ntoh(self.inner.s6_addr[7])]
self.inner.segments()
}

/// Returns true for the special 'unspecified' address ::.
@@ -474,7 +475,7 @@ impl Clone for Ipv6Addr {
#[stable(feature = "rust1", since = "1.0.0")]
impl PartialEq for Ipv6Addr {
fn eq(&self, other: &Ipv6Addr) -> bool {
self.inner.s6_addr == other.inner.s6_addr
self.inner == other.inner
}
}

@@ -484,7 +485,7 @@ impl Eq for Ipv6Addr {}
#[stable(feature = "rust1", since = "1.0.0")]
impl hash::Hash for Ipv6Addr {
fn hash<H: hash::Hasher>(&self, s: &mut H) {
self.inner.s6_addr.hash(s)
self.inner.hash(s)
}
}

@@ -498,19 +499,26 @@ impl PartialOrd for Ipv6Addr {
#[stable(feature = "rust1", since = "1.0.0")]
impl Ord for Ipv6Addr {
fn cmp(&self, other: &Ipv6Addr) -> Ordering {
self.inner.s6_addr.cmp(&other.inner.s6_addr)
self.inner.cmp(&other.inner)
}
}

impl AsInner<libc::in6_addr> for Ipv6Addr {
fn as_inner(&self) -> &libc::in6_addr { &self.inner }
impl AsInner<sys::AddrV6> for Ipv6Addr {
fn as_inner(&self) -> &sys::AddrV6 { &self.inner }
}
impl FromInner<libc::in6_addr> for Ipv6Addr {
fn from_inner(addr: libc::in6_addr) -> Ipv6Addr {

impl FromInner<sys::AddrV6> for Ipv6Addr {
fn from_inner(addr: sys::AddrV6) -> Ipv6Addr {
Ipv6Addr { inner: addr }
}
}

impl<'a> FromInner<&'a sys::AddrV6> for &'a Ipv6Addr {
fn from_inner(addr: &'a sys::AddrV6) -> &'a Ipv6Addr {
unsafe { mem::transmute(addr) }
}
}

// Tests for this module
#[cfg(test)]
mod tests {
@@ -13,9 +13,12 @@
#![stable(feature = "rust1", since = "1.0.0")]

use prelude::v1::*;
use sys::inner::prelude::*;
use sys::net::traits::*;
use sys::net::prelude as sys;
use sys::error::prelude as error;

use io::{self, Error, ErrorKind};
use sys_common::net as net_imp;

pub use self::ip::{IpAddr, Ipv4Addr, Ipv6Addr, Ipv6MulticastScope};
pub use self::addr::{SocketAddr, SocketAddrV4, SocketAddrV6, ToSocketAddrs};
@@ -49,30 +52,24 @@ pub enum Shutdown {
Both,
}

#[doc(hidden)]
trait NetInt {
fn from_be(i: Self) -> Self;
fn to_be(&self) -> Self;
}
macro_rules! doit {
($($t:ident)*) => ($(impl NetInt for $t {
fn from_be(i: Self) -> Self { <$t>::from_be(i) }
fn to_be(&self) -> Self { <$t>::to_be(*self) }
})*)
impl IntoInner<sys::Shutdown> for Shutdown {
fn into_inner(self) -> sys::Shutdown {
match self {
Shutdown::Read => sys::Shutdown::Read,
Shutdown::Write => sys::Shutdown::Write,
Shutdown::Both => sys::Shutdown::Both,
}
}
}
doit! { i8 i16 i32 i64 isize u8 u16 u32 u64 usize }

fn hton<I: NetInt>(i: I) -> I { i.to_be() }
fn ntoh<I: NetInt>(i: I) -> I { I::from_be(i) }

fn each_addr<A: ToSocketAddrs, F, T>(addr: A, mut f: F) -> io::Result<T>
where F: FnMut(&SocketAddr) -> io::Result<T>
where F: FnMut(&sys::SocketAddr) -> error::Result<T>
{
let mut last_err = None;
for addr in try!(addr.to_socket_addrs()) {
match f(&addr) {
match f(&addr.into_inner()) {
Ok(l) => return Ok(l),
Err(e) => last_err = Some(e),
Err(e) => last_err = Some(e.into()),
}
}
Err(last_err.unwrap_or_else(|| {
@@ -86,15 +83,15 @@ fn each_addr<A: ToSocketAddrs, F, T>(addr: A, mut f: F) -> io::Result<T>
iterator and returning socket \
addresses",
issue = "27705")]
pub struct LookupHost(net_imp::LookupHost);
pub struct LookupHost(sys::LookupHost);

#[unstable(feature = "lookup_host", reason = "unsure about the returned \
iterator and returning socket \
addresses",
issue = "27705")]
impl Iterator for LookupHost {
type Item = io::Result<SocketAddr>;
fn next(&mut self) -> Option<io::Result<SocketAddr>> { self.0.next() }
fn next(&mut self) -> Option<io::Result<SocketAddr>> { self.0.next().map(|i| i.map(FromInner::from_inner).map_err(From::from)) }
}

/// Resolve the host specified by `host` as a number of `SocketAddr` instances.
@@ -121,7 +118,7 @@ impl Iterator for LookupHost {
addresses",
issue = "27705")]
pub fn lookup_host(host: &str) -> io::Result<LookupHost> {
net_imp::lookup_host(host).map(LookupHost)
sys::Net::lookup_host(host).map(LookupHost).map_err(From::from)
}

/// Resolve the given address to a hostname.
@@ -132,5 +129,5 @@ pub fn lookup_host(host: &str) -> io::Result<LookupHost> {
#[unstable(feature = "lookup_addr", reason = "recent addition",
issue = "27705")]
pub fn lookup_addr(addr: &IpAddr) -> io::Result<String> {
net_imp::lookup_addr(addr)
sys::Net::lookup_addr(&addr.into_inner()).map(|a| String::from_utf8_lossy(a.as_bytes()).into_owned()).map_err(From::from)
}
@@ -10,13 +10,15 @@

use prelude::v1::*;
use io::prelude::*;
use sys::inner::prelude::*;
use sys::io::traits::*;
use sys::net::traits::*;
use sys::net::prelude as sys;

use fmt;
use io;
use net::{ToSocketAddrs, SocketAddr, Shutdown};
use sys_common::io::read_to_end_uninitialized;
use sys_common::net as net_imp;
use sys_common::{AsInner, FromInner, IntoInner};
use io::read_to_end_uninitialized;
use time::Duration;

/// A structure which represents a TCP stream between a local socket and a
@@ -39,7 +41,7 @@ use time::Duration;
/// } // the stream is closed here
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub struct TcpStream(net_imp::TcpStream);
pub struct TcpStream(sys::TcpStream);

/// A structure representing a socket server.
///
@@ -72,7 +74,7 @@ pub struct TcpStream(net_imp::TcpStream);
/// drop(listener);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub struct TcpListener(net_imp::TcpListener);
pub struct TcpListener(sys::TcpListener);

/// An infinite iterator over the connections from a `TcpListener`.
///
@@ -89,19 +91,19 @@ impl TcpStream {
/// documentation for concrete examples.
#[stable(feature = "rust1", since = "1.0.0")]
pub fn connect<A: ToSocketAddrs>(addr: A) -> io::Result<TcpStream> {
super::each_addr(addr, net_imp::TcpStream::connect).map(TcpStream)
super::each_addr(addr, sys::Net::connect_tcp).map(TcpStream)
}

/// Returns the socket address of the remote peer of this TCP connection.
#[stable(feature = "rust1", since = "1.0.0")]
pub fn peer_addr(&self) -> io::Result<SocketAddr> {
self.0.peer_addr()
self.0.peer_addr().map(FromInner::from_inner).map_err(From::from)
}

/// Returns the socket address of the local half of this TCP connection.
#[stable(feature = "rust1", since = "1.0.0")]
pub fn local_addr(&self) -> io::Result<SocketAddr> {
self.0.socket_addr()
self.0.socket_addr().map(FromInner::from_inner).map_err(From::from)
}

/// Shuts down the read, write, or both halves of this connection.
@@ -111,7 +113,7 @@ impl TcpStream {
/// documentation of `Shutdown`).
#[stable(feature = "rust1", since = "1.0.0")]
pub fn shutdown(&self, how: Shutdown) -> io::Result<()> {
self.0.shutdown(how)
self.0.shutdown(how.into_inner()).map_err(From::from)
}

/// Creates a new independently owned handle to the underlying socket.
@@ -122,7 +124,7 @@ impl TcpStream {
/// stream.
#[stable(feature = "rust1", since = "1.0.0")]
pub fn try_clone(&self) -> io::Result<TcpStream> {
self.0.duplicate().map(TcpStream)
self.0.duplicate().map(TcpStream).map_err(From::from)
}

/// Sets the read timeout to the timeout specified.
@@ -138,7 +140,7 @@ impl TcpStream {
/// error of the kind `WouldBlock`, but Windows may return `TimedOut`.
#[stable(feature = "socket_timeout", since = "1.4.0")]
pub fn set_read_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
self.0.set_read_timeout(dur)
self.0.set_read_timeout(dur).map_err(From::from)
}

/// Sets the write timeout to the timeout specified.
@@ -154,7 +156,7 @@ impl TcpStream {
/// an error of the kind `WouldBlock`, but Windows may return `TimedOut`.
#[stable(feature = "socket_timeout", since = "1.4.0")]
pub fn set_write_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
self.0.set_write_timeout(dur)
self.0.set_write_timeout(dur).map_err(From::from)
}

/// Returns the read timeout of this socket.
@@ -166,7 +168,7 @@ impl TcpStream {
/// Some platforms do not provide access to the current timeout.
#[stable(feature = "socket_timeout", since = "1.4.0")]
pub fn read_timeout(&self) -> io::Result<Option<Duration>> {
self.0.read_timeout()
self.0.read_timeout().map_err(From::from)
}

/// Returns the write timeout of this socket.
@@ -178,50 +180,62 @@ impl TcpStream {
/// Some platforms do not provide access to the current timeout.
#[stable(feature = "socket_timeout", since = "1.4.0")]
pub fn write_timeout(&self) -> io::Result<Option<Duration>> {
self.0.write_timeout()
self.0.write_timeout().map_err(From::from)
}
}

#[stable(feature = "rust1", since = "1.0.0")]
impl Read for TcpStream {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { self.0.read(buf) }
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { self.0.read(buf).map_err(From::from) }
fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
unsafe { read_to_end_uninitialized(self, buf) }
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl Write for TcpStream {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.0.write(buf) }
fn flush(&mut self) -> io::Result<()> { Ok(()) }
fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.0.write(buf).map_err(From::from) }
fn flush(&mut self) -> io::Result<()> { self.0.flush().map_err(From::from) }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a> Read for &'a TcpStream {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { self.0.read(buf) }
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { self.0.read(buf).map_err(From::from) }
fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
unsafe { read_to_end_uninitialized(self, buf) }
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a> Write for &'a TcpStream {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.0.write(buf) }
fn flush(&mut self) -> io::Result<()> { Ok(()) }
fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.0.write(buf).map_err(From::from) }
fn flush(&mut self) -> io::Result<()> { self.0.flush().map_err(From::from) }
}

impl AsInner<net_imp::TcpStream> for TcpStream {
fn as_inner(&self) -> &net_imp::TcpStream { &self.0 }
impl AsInner<sys::TcpStream> for TcpStream {
fn as_inner(&self) -> &sys::TcpStream { &self.0 }
}

impl FromInner<net_imp::TcpStream> for TcpStream {
fn from_inner(inner: net_imp::TcpStream) -> TcpStream { TcpStream(inner) }
impl FromInner<sys::TcpStream> for TcpStream {
fn from_inner(inner: sys::TcpStream) -> TcpStream { TcpStream(inner) }
}

impl IntoInner<net_imp::TcpStream> for TcpStream {
fn into_inner(self) -> net_imp::TcpStream { self.0 }
impl IntoInner<sys::TcpStream> for TcpStream {
fn into_inner(self) -> sys::TcpStream { self.0 }
}

impl fmt::Debug for TcpStream {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.0.fmt(f)
let mut res = f.debug_struct("TcpStream");

if let Ok(addr) = self.local_addr() {
res.field("addr", &addr);
}

if let Ok(addr) = self.peer_addr() {
res.field("peer_addr", &addr);
}

let name = if cfg!(windows) {"socket"} else {"fd"};
res.field(name, AsInner::<sys::Socket>::as_inner(&self.0))
.finish()
}
}

@@ -233,19 +247,19 @@ impl TcpListener {
///
/// Binding with a port number of 0 will request that the OS assigns a port
/// to this listener. The port allocated can be queried via the
/// `socket_addr` function.
/// `local_addr` function.
///
/// The address type can be any implementer of `ToSocketAddrs` trait. See
/// its documentation for concrete examples.
#[stable(feature = "rust1", since = "1.0.0")]
pub fn bind<A: ToSocketAddrs>(addr: A) -> io::Result<TcpListener> {
super::each_addr(addr, net_imp::TcpListener::bind).map(TcpListener)
super::each_addr(addr, sys::Net::bind_tcp).map(TcpListener)
}

/// Returns the local socket address of this listener.
#[stable(feature = "rust1", since = "1.0.0")]
pub fn local_addr(&self) -> io::Result<SocketAddr> {
self.0.socket_addr()
self.0.socket_addr().map(FromInner::from_inner).map_err(From::from)
}

/// Creates a new independently owned handle to the underlying socket.
@@ -255,7 +269,7 @@ impl TcpListener {
/// connections and options set on one listener will affect the other.
#[stable(feature = "rust1", since = "1.0.0")]
pub fn try_clone(&self) -> io::Result<TcpListener> {
self.0.duplicate().map(TcpListener)
self.0.duplicate().map(TcpListener).map_err(From::from)
}

/// Accept a new incoming connection from this listener.
@@ -265,7 +279,7 @@ impl TcpListener {
/// remote peer's address will be returned.
#[stable(feature = "rust1", since = "1.0.0")]
pub fn accept(&self) -> io::Result<(TcpStream, SocketAddr)> {
self.0.accept().map(|(a, b)| (TcpStream(a), b))
self.0.accept().map(|(a, b)| (TcpStream(a), FromInner::from_inner(b))).map_err(From::from)
}

/// Returns an iterator over the connections being received on this
@@ -287,23 +301,31 @@ impl<'a> Iterator for Incoming<'a> {
}
}

impl AsInner<net_imp::TcpListener> for TcpListener {
fn as_inner(&self) -> &net_imp::TcpListener { &self.0 }
impl AsInner<sys::TcpListener> for TcpListener {
fn as_inner(&self) -> &sys::TcpListener { &self.0 }
}

impl FromInner<net_imp::TcpListener> for TcpListener {
fn from_inner(inner: net_imp::TcpListener) -> TcpListener {
impl FromInner<sys::TcpListener> for TcpListener {
fn from_inner(inner: sys::TcpListener) -> TcpListener {
TcpListener(inner)
}
}

impl IntoInner<net_imp::TcpListener> for TcpListener {
fn into_inner(self) -> net_imp::TcpListener { self.0 }
impl IntoInner<sys::TcpListener> for TcpListener {
fn into_inner(self) -> sys::TcpListener { self.0 }
}

impl fmt::Debug for TcpListener {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.0.fmt(f)
let mut res = f.debug_struct("TcpListener");

if let Ok(addr) = self.local_addr() {
res.field("addr", &addr);
}

let name = if cfg!(windows) {"socket"} else {"fd"};
res.field(name, AsInner::<sys::Socket>::as_inner(&self.0))
.finish()
}
}

@@ -313,11 +335,11 @@ mod tests {

use io::ErrorKind;
use io::prelude::*;
use sys::inner::prelude::*;
use net::*;
use net::test::{next_test_ip4, next_test_ip6};
use sync::mpsc::channel;
use sys_common::AsInner;
use time::Duration;
use time::{self, Duration};
use thread;

fn each_ip(f: &mut FnMut(SocketAddr)) {
@@ -891,18 +913,20 @@ mod tests {

#[test]
fn debug() {
use sys::net::prelude as sys;

let name = if cfg!(windows) {"socket"} else {"fd"};
let socket_addr = next_test_ip4();

let listener = t!(TcpListener::bind(&socket_addr));
let listener_inner = listener.0.socket().as_inner();
let listener_inner = AsInner::<sys::Socket>::as_inner(&listener.0);
let compare = format!("TcpListener {{ addr: {:?}, {}: {:?} }}",
socket_addr, name, listener_inner);
assert_eq!(format!("{:?}", listener), compare);

let stream = t!(TcpStream::connect(&("localhost",
socket_addr.port())));
let stream_inner = stream.0.socket().as_inner();
let stream_inner = AsInner::<sys::Socket>::as_inner(&stream.0);
let compare = format!("TcpStream {{ addr: {:?}, \
peer: {:?}, {}: {:?} }}",
stream.local_addr().unwrap(),
@@ -949,7 +973,7 @@ mod tests {
t!(stream.set_read_timeout(Some(Duration::from_millis(1000))));

let mut buf = [0; 10];
let wait = Duration::span(|| {
let wait = time::span(|| {
let kind = stream.read(&mut buf).err().expect("expected error").kind();
assert!(kind == ErrorKind::WouldBlock || kind == ErrorKind::TimedOut);
});
@@ -971,7 +995,7 @@ mod tests {
t!(stream.read(&mut buf));
assert_eq!(b"hello world", &buf[..]);

let wait = Duration::span(|| {
let wait = time::span(|| {
let kind = stream.read(&mut buf).err().expect("expected error").kind();
assert!(kind == ErrorKind::WouldBlock || kind == ErrorKind::TimedOut);
});
@@ -8,11 +8,13 @@
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use sys::inner::prelude::*;
use sys::net::traits::*;
use sys::net::prelude as sys;

use fmt;
use io::{self, Error, ErrorKind};
use net::{ToSocketAddrs, SocketAddr};
use sys_common::net as net_imp;
use sys_common::{AsInner, FromInner, IntoInner};
use time::Duration;

/// A User Datagram Protocol socket.
@@ -42,7 +44,7 @@ use time::Duration;
/// # }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub struct UdpSocket(net_imp::UdpSocket);
pub struct UdpSocket(sys::UdpSocket);

impl UdpSocket {
/// Creates a UDP socket from the given address.
@@ -51,14 +53,14 @@ impl UdpSocket {
/// its documentation for concrete examples.
#[stable(feature = "rust1", since = "1.0.0")]
pub fn bind<A: ToSocketAddrs>(addr: A) -> io::Result<UdpSocket> {
super::each_addr(addr, net_imp::UdpSocket::bind).map(UdpSocket)
super::each_addr(addr, sys::Net::bind_udp).map(UdpSocket).map_err(From::from)
}

/// Receives data from the socket. On success, returns the number of bytes
/// read and the address from whence the data came.
#[stable(feature = "rust1", since = "1.0.0")]
pub fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
self.0.recv_from(buf)
self.0.recv_from(buf).map(|(s, a)| (s, FromInner::from_inner(a))).map_err(From::from)
}

/// Sends data on the socket to the given address. On success, returns the
@@ -70,7 +72,7 @@ impl UdpSocket {
pub fn send_to<A: ToSocketAddrs>(&self, buf: &[u8], addr: A)
-> io::Result<usize> {
match try!(addr.to_socket_addrs()).next() {
Some(addr) => self.0.send_to(buf, &addr),
Some(addr) => self.0.send_to(buf, &addr.into_inner()).map_err(From::from),
None => Err(Error::new(ErrorKind::InvalidInput,
"no addresses to send data to")),
}
@@ -79,7 +81,7 @@ impl UdpSocket {
/// Returns the socket address that this socket was created from.
#[stable(feature = "rust1", since = "1.0.0")]
pub fn local_addr(&self) -> io::Result<SocketAddr> {
self.0.socket_addr()
self.0.socket_addr().map(FromInner::from_inner).map_err(From::from)
}

/// Creates a new independently owned handle to the underlying socket.
@@ -89,7 +91,7 @@ impl UdpSocket {
/// options set on one socket will be propagated to the other.
#[stable(feature = "rust1", since = "1.0.0")]
pub fn try_clone(&self) -> io::Result<UdpSocket> {
self.0.duplicate().map(UdpSocket)
self.0.duplicate().map(UdpSocket).map_err(From::from)
}

/// Sets the read timeout to the timeout specified.
@@ -105,7 +107,7 @@ impl UdpSocket {
/// error of the kind `WouldBlock`, but Windows may return `TimedOut`.
#[stable(feature = "socket_timeout", since = "1.4.0")]
pub fn set_read_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
self.0.set_read_timeout(dur)
self.0.set_read_timeout(dur).map_err(From::from)
}

/// Sets the write timeout to the timeout specified.
@@ -121,54 +123,63 @@ impl UdpSocket {
/// an error of the kind `WouldBlock`, but Windows may return `TimedOut`.
#[stable(feature = "socket_timeout", since = "1.4.0")]
pub fn set_write_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
self.0.set_write_timeout(dur)
self.0.set_write_timeout(dur).map_err(From::from)
}

/// Returns the read timeout of this socket.
///
/// If the timeout is `None`, then `read` calls will block indefinitely.
#[stable(feature = "socket_timeout", since = "1.4.0")]
pub fn read_timeout(&self) -> io::Result<Option<Duration>> {
self.0.read_timeout()
self.0.read_timeout().map_err(From::from)
}

/// Returns the write timeout of this socket.
///
/// If the timeout is `None`, then `write` calls will block indefinitely.
#[stable(feature = "socket_timeout", since = "1.4.0")]
pub fn write_timeout(&self) -> io::Result<Option<Duration>> {
self.0.write_timeout()
self.0.write_timeout().map_err(From::from)
}
}

impl AsInner<net_imp::UdpSocket> for UdpSocket {
fn as_inner(&self) -> &net_imp::UdpSocket { &self.0 }
impl AsInner<sys::UdpSocket> for UdpSocket {
fn as_inner(&self) -> &sys::UdpSocket { &self.0 }
}

impl FromInner<net_imp::UdpSocket> for UdpSocket {
fn from_inner(inner: net_imp::UdpSocket) -> UdpSocket { UdpSocket(inner) }
impl FromInner<sys::UdpSocket> for UdpSocket {
fn from_inner(inner: sys::UdpSocket) -> UdpSocket { UdpSocket(inner) }
}

impl IntoInner<net_imp::UdpSocket> for UdpSocket {
fn into_inner(self) -> net_imp::UdpSocket { self.0 }
impl IntoInner<sys::UdpSocket> for UdpSocket {
fn into_inner(self) -> sys::UdpSocket { self.0 }
}

impl fmt::Debug for UdpSocket {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.0.fmt(f)
let mut res = f.debug_struct("UdpSocket");

if let Ok(addr) = self.local_addr() {
res.field("addr", &addr);
}

let name = if cfg!(windows) {"socket"} else {"fd"};
res.field(name, AsInner::<sys::Socket>::as_inner(&self.0))
.finish()
}
}


#[cfg(test)]
mod tests {
use prelude::v1::*;

use sys::inner::prelude::*;
use io::ErrorKind;
use net::*;
use net::test::{next_test_ip4, next_test_ip6};
use sync::mpsc::channel;
use sys_common::AsInner;
use time::Duration;
use time::{self, Duration};
use thread;

fn each_ip(f: &mut FnMut(SocketAddr, SocketAddr)) {
@@ -328,11 +339,13 @@ mod tests {

#[test]
fn debug() {
use sys::net::prelude as sys;

let name = if cfg!(windows) {"socket"} else {"fd"};
let socket_addr = next_test_ip4();

let udpsock = t!(UdpSocket::bind(&socket_addr));
let udpsock_inner = udpsock.0.socket().as_inner();
let udpsock_inner = AsInner::<sys::Socket>::as_inner(&udpsock.0);
let compare = format!("UdpSocket {{ addr: {:?}, {}: {:?} }}",
socket_addr, name, udpsock_inner);
assert_eq!(format!("{:?}", udpsock), compare);
@@ -373,7 +386,7 @@ mod tests {
t!(stream.set_read_timeout(Some(Duration::from_millis(1000))));

let mut buf = [0; 10];
let wait = Duration::span(|| {
let wait = time::span(|| {
let kind = stream.recv_from(&mut buf).err().expect("expected error").kind();
assert!(kind == ErrorKind::WouldBlock || kind == ErrorKind::TimedOut);
});
@@ -393,7 +406,7 @@ mod tests {
t!(stream.recv_from(&mut buf));
assert_eq!(b"hello world", &buf[..]);

let wait = Duration::span(|| {
let wait = time::span(|| {
let kind = stream.recv_from(&mut buf).err().expect("expected error").kind();
assert!(kind == ErrorKind::WouldBlock || kind == ErrorKind::TimedOut);
});
Oops, something went wrong.