file_name large_stringlengths 4 69 | prefix large_stringlengths 0 26.7k | suffix large_stringlengths 0 24.8k | middle large_stringlengths 0 2.12k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
statusbar.rs | // This file is part of rgtk.
//
// rgtk is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// rgtk is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with rgtk. If not, see <http://www.gnu.org/licenses/>.
//! An adapter which makes widgets scrollable
use gtk::cast::GTK_STATUSBAR;
use gtk::{mod, ffi};
/// GtkViewport — An adapter which makes widgets scrollable
struct_Widget!(StatusBar)
impl StatusBar {
pub fn ne | -> Option<StatusBar> {
let tmp_pointer = unsafe { ffi::gtk_statusbar_new() };
check_pointer!(tmp_pointer, StatusBar)
}
pub fn push(&mut self, context_id: u32, text: &str) -> u32 {
unsafe {
text.with_c_str(|c_str| {
ffi::gtk_statusbar_push(GTK_STATUSBAR(self.pointer),
context_id,
c_str)
})
}
}
pub fn pop(&mut self, context_id: u32) {
unsafe {
ffi::gtk_statusbar_pop(GTK_STATUSBAR(self.pointer), context_id)
}
}
pub fn remove(&mut self, context_id: u32, message_id: u32) {
unsafe {
ffi::gtk_statusbar_remove(GTK_STATUSBAR(self.pointer), context_id, message_id)
}
}
pub fn remove_all(&mut self, context_id: u32) {
unsafe {
ffi::gtk_statusbar_remove_all(GTK_STATUSBAR(self.pointer), context_id)
}
}
pub fn get_message_area<T: gtk::WidgetTrait + gtk::BoxTrait>(&self) -> T {
unsafe {
ffi::FFIWidget::wrap(ffi::gtk_statusbar_get_message_area(GTK_STATUSBAR(self.pointer)))
}
}
}
impl_drop!(StatusBar)
impl_TraitWidget!(StatusBar)
impl gtk::ContainerTrait for StatusBar {}
impl gtk::BoxTrait for StatusBar {}
impl gtk::OrientableTrait for StatusBar {}
impl_widget_events!(StatusBar)
| w() | identifier_name |
statusbar.rs | // This file is part of rgtk.
//
// rgtk is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// rgtk is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with rgtk. If not, see <http://www.gnu.org/licenses/>.
//! An adapter which makes widgets scrollable
use gtk::cast::GTK_STATUSBAR;
use gtk::{mod, ffi};
/// GtkViewport — An adapter which makes widgets scrollable
struct_Widget!(StatusBar)
impl StatusBar {
pub fn new() -> Option<StatusBar> {
let tmp_pointer = unsafe { ffi::gtk_statusbar_new() };
check_pointer!(tmp_pointer, StatusBar)
}
pub fn push(&mut self, context_id: u32, text: &str) -> u32 {
unsafe {
text.with_c_str(|c_str| {
ffi::gtk_statusbar_push(GTK_STATUSBAR(self.pointer),
context_id,
c_str)
})
}
}
pub fn pop(&mut self, context_id: u32) {
| pub fn remove(&mut self, context_id: u32, message_id: u32) {
unsafe {
ffi::gtk_statusbar_remove(GTK_STATUSBAR(self.pointer), context_id, message_id)
}
}
pub fn remove_all(&mut self, context_id: u32) {
unsafe {
ffi::gtk_statusbar_remove_all(GTK_STATUSBAR(self.pointer), context_id)
}
}
pub fn get_message_area<T: gtk::WidgetTrait + gtk::BoxTrait>(&self) -> T {
unsafe {
ffi::FFIWidget::wrap(ffi::gtk_statusbar_get_message_area(GTK_STATUSBAR(self.pointer)))
}
}
}
impl_drop!(StatusBar)
impl_TraitWidget!(StatusBar)
impl gtk::ContainerTrait for StatusBar {}
impl gtk::BoxTrait for StatusBar {}
impl gtk::OrientableTrait for StatusBar {}
impl_widget_events!(StatusBar)
| unsafe {
ffi::gtk_statusbar_pop(GTK_STATUSBAR(self.pointer), context_id)
}
}
| identifier_body |
statusbar.rs | // This file is part of rgtk.
//
// rgtk is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// rgtk is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License | use gtk::{mod, ffi};
/// GtkViewport — An adapter which makes widgets scrollable
struct_Widget!(StatusBar)
impl StatusBar {
pub fn new() -> Option<StatusBar> {
let tmp_pointer = unsafe { ffi::gtk_statusbar_new() };
check_pointer!(tmp_pointer, StatusBar)
}
pub fn push(&mut self, context_id: u32, text: &str) -> u32 {
unsafe {
text.with_c_str(|c_str| {
ffi::gtk_statusbar_push(GTK_STATUSBAR(self.pointer),
context_id,
c_str)
})
}
}
pub fn pop(&mut self, context_id: u32) {
unsafe {
ffi::gtk_statusbar_pop(GTK_STATUSBAR(self.pointer), context_id)
}
}
pub fn remove(&mut self, context_id: u32, message_id: u32) {
unsafe {
ffi::gtk_statusbar_remove(GTK_STATUSBAR(self.pointer), context_id, message_id)
}
}
pub fn remove_all(&mut self, context_id: u32) {
unsafe {
ffi::gtk_statusbar_remove_all(GTK_STATUSBAR(self.pointer), context_id)
}
}
pub fn get_message_area<T: gtk::WidgetTrait + gtk::BoxTrait>(&self) -> T {
unsafe {
ffi::FFIWidget::wrap(ffi::gtk_statusbar_get_message_area(GTK_STATUSBAR(self.pointer)))
}
}
}
impl_drop!(StatusBar)
impl_TraitWidget!(StatusBar)
impl gtk::ContainerTrait for StatusBar {}
impl gtk::BoxTrait for StatusBar {}
impl gtk::OrientableTrait for StatusBar {}
impl_widget_events!(StatusBar) | // along with rgtk. If not, see <http://www.gnu.org/licenses/>.
//! An adapter which makes widgets scrollable
use gtk::cast::GTK_STATUSBAR; | random_line_split |
build.rs | //#![feature(plugin)]
//#![plugin(bindgen_plugin)]
//#[allow(dead_code, uppercase_variables, non_camel_case_types)]
//#[plugin(bindgen_plugin)]
//mod mysql_bindings {
// bindgen!("/usr/include/mysql/mysql.h", match="mysql.h", link="mysql");
//}
//use std::env;
//use std::fs;
//use std::path::Path;
//use std::process::Command;
extern crate libbindgen;
use std::env;
use std::path::Path;
fn main() {
let _ = libbindgen::builder()
.header("cassandra.h")
.use_core()
.generate().unwrap()
.write_to_file(Path::new("./src/").join("cassandra.rs"));
if let Some(datastax_dir) = option_env!("CASSANDRA_SYS_LIB_PATH") |
println!("cargo:rustc-flags=-l dylib=crypto");
println!("cargo:rustc-flags=-l dylib=ssl");
println!("cargo:rustc-flags=-l dylib=stdc++");
println!("cargo:rustc-flags=-l dylib=uv");
println!("cargo:rustc-link-search={}", "/usr/lib/x86_64-linux-gnu");
println!("cargo:rustc-link-search={}", "/usr/local/lib/x86_64-linux-gnu");
println!("cargo:rustc-link-search={}", "/usr/local/lib64");
println!("cargo:rustc-link-search={}", "/usr/local/lib");
println!("cargo:rustc-link-search={}", "/usr/lib64/");
println!("cargo:rustc-link-search={}", "/usr/lib/");
println!("cargo:rustc-link-lib=static=cassandra_static");
}
| {
for p in datastax_dir.split(";") {
println!("cargo:rustc-link-search={}", p);
}
} | conditional_block |
build.rs | //#![feature(plugin)]
//#![plugin(bindgen_plugin)]
//#[allow(dead_code, uppercase_variables, non_camel_case_types)]
//#[plugin(bindgen_plugin)]
//mod mysql_bindings {
// bindgen!("/usr/include/mysql/mysql.h", match="mysql.h", link="mysql");
//}
//use std::env;
//use std::fs;
//use std::path::Path;
//use std::process::Command;
extern crate libbindgen;
use std::env;
use std::path::Path;
fn main() | println!("cargo:rustc-link-search={}", "/usr/local/lib");
println!("cargo:rustc-link-search={}", "/usr/lib64/");
println!("cargo:rustc-link-search={}", "/usr/lib/");
println!("cargo:rustc-link-lib=static=cassandra_static");
}
| {
let _ = libbindgen::builder()
.header("cassandra.h")
.use_core()
.generate().unwrap()
.write_to_file(Path::new("./src/").join("cassandra.rs"));
if let Some(datastax_dir) = option_env!("CASSANDRA_SYS_LIB_PATH") {
for p in datastax_dir.split(";") {
println!("cargo:rustc-link-search={}", p);
}
}
println!("cargo:rustc-flags=-l dylib=crypto");
println!("cargo:rustc-flags=-l dylib=ssl");
println!("cargo:rustc-flags=-l dylib=stdc++");
println!("cargo:rustc-flags=-l dylib=uv");
println!("cargo:rustc-link-search={}", "/usr/lib/x86_64-linux-gnu");
println!("cargo:rustc-link-search={}", "/usr/local/lib/x86_64-linux-gnu");
println!("cargo:rustc-link-search={}", "/usr/local/lib64"); | identifier_body |
build.rs | //#![feature(plugin)]
//#![plugin(bindgen_plugin)]
//#[allow(dead_code, uppercase_variables, non_camel_case_types)]
//#[plugin(bindgen_plugin)]
//mod mysql_bindings {
// bindgen!("/usr/include/mysql/mysql.h", match="mysql.h", link="mysql");
//}
//use std::env;
//use std::fs;
//use std::path::Path;
//use std::process::Command;
extern crate libbindgen;
use std::env;
use std::path::Path;
fn main() {
let _ = libbindgen::builder()
.header("cassandra.h")
.use_core()
.generate().unwrap()
.write_to_file(Path::new("./src/").join("cassandra.rs"));
if let Some(datastax_dir) = option_env!("CASSANDRA_SYS_LIB_PATH") {
for p in datastax_dir.split(";") {
println!("cargo:rustc-link-search={}", p);
}
}
println!("cargo:rustc-flags=-l dylib=crypto");
println!("cargo:rustc-flags=-l dylib=ssl");
println!("cargo:rustc-flags=-l dylib=stdc++");
println!("cargo:rustc-flags=-l dylib=uv");
println!("cargo:rustc-link-search={}", "/usr/lib/x86_64-linux-gnu");
println!("cargo:rustc-link-search={}", "/usr/local/lib/x86_64-linux-gnu");
println!("cargo:rustc-link-search={}", "/usr/local/lib64"); | println!("cargo:rustc-link-search={}", "/usr/local/lib");
println!("cargo:rustc-link-search={}", "/usr/lib64/");
println!("cargo:rustc-link-search={}", "/usr/lib/");
println!("cargo:rustc-link-lib=static=cassandra_static");
} | random_line_split | |
build.rs | //#![feature(plugin)]
//#![plugin(bindgen_plugin)]
//#[allow(dead_code, uppercase_variables, non_camel_case_types)]
//#[plugin(bindgen_plugin)]
//mod mysql_bindings {
// bindgen!("/usr/include/mysql/mysql.h", match="mysql.h", link="mysql");
//}
//use std::env;
//use std::fs;
//use std::path::Path;
//use std::process::Command;
extern crate libbindgen;
use std::env;
use std::path::Path;
fn | () {
let _ = libbindgen::builder()
.header("cassandra.h")
.use_core()
.generate().unwrap()
.write_to_file(Path::new("./src/").join("cassandra.rs"));
if let Some(datastax_dir) = option_env!("CASSANDRA_SYS_LIB_PATH") {
for p in datastax_dir.split(";") {
println!("cargo:rustc-link-search={}", p);
}
}
println!("cargo:rustc-flags=-l dylib=crypto");
println!("cargo:rustc-flags=-l dylib=ssl");
println!("cargo:rustc-flags=-l dylib=stdc++");
println!("cargo:rustc-flags=-l dylib=uv");
println!("cargo:rustc-link-search={}", "/usr/lib/x86_64-linux-gnu");
println!("cargo:rustc-link-search={}", "/usr/local/lib/x86_64-linux-gnu");
println!("cargo:rustc-link-search={}", "/usr/local/lib64");
println!("cargo:rustc-link-search={}", "/usr/local/lib");
println!("cargo:rustc-link-search={}", "/usr/lib64/");
println!("cargo:rustc-link-search={}", "/usr/lib/");
println!("cargo:rustc-link-lib=static=cassandra_static");
}
| main | identifier_name |
pending.rs | use core::marker;
use core::pin::Pin;
use futures_core::future::{FusedFuture, Future};
use futures_core::task::{Context, Poll};
/// Future for the [`pending()`] function.
#[derive(Debug)]
#[must_use = "futures do nothing unless you `.await` or poll them"]
pub struct Pending<T> {
_data: marker::PhantomData<T>,
}
impl<T> FusedFuture for Pending<T> {
fn is_terminated(&self) -> bool {
true
}
}
/// Creates a future which never resolves, representing a computation that never
/// finishes.
///
/// The returned future will forever return [`Poll::Pending`].
///
/// # Examples
///
/// ```ignore
/// # futures::executor::block_on(async {
/// use futures::future;
///
/// let future = future::pending();
/// let () = future.await;
/// unreachable!();
/// # });
/// ```
pub fn pending<T>() -> Pending<T> {
Pending {
_data: marker::PhantomData,
}
}
impl<T> Future for Pending<T> {
type Output = T;
fn poll(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<T> {
Poll::Pending
}
}
impl<T> Unpin for Pending<T> {
}
impl<T> Clone for Pending<T> {
fn | (&self) -> Self {
pending()
}
}
| clone | identifier_name |
pending.rs | use core::marker;
use core::pin::Pin;
use futures_core::future::{FusedFuture, Future};
use futures_core::task::{Context, Poll};
/// Future for the [`pending()`] function. | pub struct Pending<T> {
_data: marker::PhantomData<T>,
}
impl<T> FusedFuture for Pending<T> {
fn is_terminated(&self) -> bool {
true
}
}
/// Creates a future which never resolves, representing a computation that never
/// finishes.
///
/// The returned future will forever return [`Poll::Pending`].
///
/// # Examples
///
/// ```ignore
/// # futures::executor::block_on(async {
/// use futures::future;
///
/// let future = future::pending();
/// let () = future.await;
/// unreachable!();
/// # });
/// ```
pub fn pending<T>() -> Pending<T> {
Pending {
_data: marker::PhantomData,
}
}
impl<T> Future for Pending<T> {
type Output = T;
fn poll(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<T> {
Poll::Pending
}
}
impl<T> Unpin for Pending<T> {
}
impl<T> Clone for Pending<T> {
fn clone(&self) -> Self {
pending()
}
} | #[derive(Debug)]
#[must_use = "futures do nothing unless you `.await` or poll them"] | random_line_split |
conversions.rs | use std::str::FromStr;
use super::errors::TcpTransportError;
use super::typedefs::TcpTransportResult;
pub fn as_string(bytes: Vec<u8>) -> TcpTransportResult<String> {
match String::from_utf8(bytes) {
Ok(st) => Ok(st),
Err(_) => Err(TcpTransportError::Utf8Error),
}
}
pub fn as_number<N: FromStr>(bytes: Vec<u8>) -> TcpTransportResult<N> {
let string = try!(as_string(bytes));
match string.parse::<N>() {
Ok(num) => Ok(num),
Err(_) => Err(TcpTransportError::NumberParseError),
}
}
#[cfg(test)]
mod tests {
use tcp_transport::TcpTransportError;
use super::as_number;
use super::as_string;
#[test] |
// bytestring is not utf8
let err = as_string(vec![b'a', 254, b'b']).unwrap_err();
assert_eq!(err, TcpTransportError::Utf8Error);
}
#[test]
fn test_as_number() {
// bytestring is a number
let num = as_number::<u64>(vec![b'1', b'2']).unwrap();
assert_eq!(num, 12);
// bytestring is not a number
let err = as_number::<u64>(vec![b' ', b'1', b'2']).unwrap_err();
assert_eq!(err, TcpTransportError::NumberParseError);
}
} | fn test_as_string() {
// bytestring is utf8
let st = as_string(vec![b'a', b'b']).unwrap();
assert_eq!(st, "ab".to_string()); | random_line_split |
conversions.rs | use std::str::FromStr;
use super::errors::TcpTransportError;
use super::typedefs::TcpTransportResult;
pub fn | (bytes: Vec<u8>) -> TcpTransportResult<String> {
match String::from_utf8(bytes) {
Ok(st) => Ok(st),
Err(_) => Err(TcpTransportError::Utf8Error),
}
}
pub fn as_number<N: FromStr>(bytes: Vec<u8>) -> TcpTransportResult<N> {
let string = try!(as_string(bytes));
match string.parse::<N>() {
Ok(num) => Ok(num),
Err(_) => Err(TcpTransportError::NumberParseError),
}
}
#[cfg(test)]
mod tests {
use tcp_transport::TcpTransportError;
use super::as_number;
use super::as_string;
#[test]
fn test_as_string() {
// bytestring is utf8
let st = as_string(vec![b'a', b'b']).unwrap();
assert_eq!(st, "ab".to_string());
// bytestring is not utf8
let err = as_string(vec![b'a', 254, b'b']).unwrap_err();
assert_eq!(err, TcpTransportError::Utf8Error);
}
#[test]
fn test_as_number() {
// bytestring is a number
let num = as_number::<u64>(vec![b'1', b'2']).unwrap();
assert_eq!(num, 12);
// bytestring is not a number
let err = as_number::<u64>(vec![b' ', b'1', b'2']).unwrap_err();
assert_eq!(err, TcpTransportError::NumberParseError);
}
}
| as_string | identifier_name |
conversions.rs | use std::str::FromStr;
use super::errors::TcpTransportError;
use super::typedefs::TcpTransportResult;
pub fn as_string(bytes: Vec<u8>) -> TcpTransportResult<String> {
match String::from_utf8(bytes) {
Ok(st) => Ok(st),
Err(_) => Err(TcpTransportError::Utf8Error),
}
}
pub fn as_number<N: FromStr>(bytes: Vec<u8>) -> TcpTransportResult<N> |
#[cfg(test)]
mod tests {
use tcp_transport::TcpTransportError;
use super::as_number;
use super::as_string;
#[test]
fn test_as_string() {
// bytestring is utf8
let st = as_string(vec![b'a', b'b']).unwrap();
assert_eq!(st, "ab".to_string());
// bytestring is not utf8
let err = as_string(vec![b'a', 254, b'b']).unwrap_err();
assert_eq!(err, TcpTransportError::Utf8Error);
}
#[test]
fn test_as_number() {
// bytestring is a number
let num = as_number::<u64>(vec![b'1', b'2']).unwrap();
assert_eq!(num, 12);
// bytestring is not a number
let err = as_number::<u64>(vec![b' ', b'1', b'2']).unwrap_err();
assert_eq!(err, TcpTransportError::NumberParseError);
}
}
| {
let string = try!(as_string(bytes));
match string.parse::<N>() {
Ok(num) => Ok(num),
Err(_) => Err(TcpTransportError::NumberParseError),
}
} | identifier_body |
os.rs | // 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.
//! Implementation of `std::os` functionality for unix systems
#![allow(unused_imports)] // lots of cfg code here
use prelude::v1::*;
use os::unix::prelude::*;
use error::Error as StdError;
use ffi::{CString, CStr, OsString, OsStr};
use fmt;
use io;
use iter;
use libc::{self, c_int, c_char, c_void};
use mem;
use ptr;
use path::{self, PathBuf};
use slice;
use str;
use sys::c;
use sys::fd;
use vec;
const BUF_BYTES: usize = 2048;
const TMPBUF_SZ: usize = 128;
fn bytes2path(b: &[u8]) -> PathBuf {
PathBuf::from(<OsStr as OsStrExt>::from_bytes(b))
}
fn os2path(os: OsString) -> PathBuf {
bytes2path(os.as_bytes())
}
/// Returns the platform-specific value of errno
pub fn errno() -> i32 {
#[cfg(any(target_os = "macos",
target_os = "ios",
target_os = "freebsd"))]
unsafe fn errno_location() -> *const c_int {
extern { fn __error() -> *const c_int; }
__error()
}
#[cfg(target_os = "bitrig")]
fn errno_location() -> *const c_int {
extern {
fn __errno() -> *const c_int;
}
unsafe {
__errno()
}
}
#[cfg(target_os = "dragonfly")]
unsafe fn errno_location() -> *const c_int {
extern { fn __dfly_error() -> *const c_int; }
__dfly_error()
}
#[cfg(target_os = "openbsd")]
unsafe fn errno_location() -> *const c_int {
extern { fn __errno() -> *const c_int; }
__errno()
}
#[cfg(any(target_os = "linux", target_os = "android"))]
unsafe fn errno_location() -> *const c_int {
extern { fn __errno_location() -> *const c_int; }
__errno_location()
}
unsafe {
(*errno_location()) as i32
}
}
/// Gets a detailed string description for the given error number.
pub fn error_string(errno: i32) -> String {
#[cfg(target_os = "linux")]
extern {
#[link_name = "__xpg_strerror_r"]
fn strerror_r(errnum: c_int, buf: *mut c_char,
buflen: libc::size_t) -> c_int;
}
#[cfg(not(target_os = "linux"))]
extern {
fn strerror_r(errnum: c_int, buf: *mut c_char,
buflen: libc::size_t) -> c_int;
}
let mut buf = [0 as c_char; TMPBUF_SZ];
let p = buf.as_mut_ptr();
unsafe {
if strerror_r(errno as c_int, p, buf.len() as libc::size_t) < 0 {
panic!("strerror_r failure");
}
let p = p as *const _;
str::from_utf8(CStr::from_ptr(p).to_bytes()).unwrap().to_string()
}
}
pub fn getcwd() -> io::Result<PathBuf> {
let mut buf = [0 as c_char; BUF_BYTES];
unsafe {
if libc::getcwd(buf.as_mut_ptr(), buf.len() as libc::size_t).is_null() {
Err(io::Error::last_os_error())
} else {
Ok(bytes2path(CStr::from_ptr(buf.as_ptr()).to_bytes()))
}
}
}
pub fn chdir(p: &path::Path) -> io::Result<()> {
let p: &OsStr = p.as_ref();
let p = try!(CString::new(p.as_bytes()));
unsafe {
match libc::chdir(p.as_ptr()) == (0 as c_int) {
true => Ok(()),
false => Err(io::Error::last_os_error()),
}
}
}
pub struct SplitPaths<'a> {
iter: iter::Map<slice::Split<'a, u8, fn(&u8) -> bool>,
fn(&'a [u8]) -> PathBuf>,
}
pub fn split_paths<'a>(unparsed: &'a OsStr) -> SplitPaths<'a> {
fn is_colon(b: &u8) -> bool { *b == b':' }
let unparsed = unparsed.as_bytes();
SplitPaths {
iter: unparsed.split(is_colon as fn(&u8) -> bool)
.map(bytes2path as fn(&'a [u8]) -> PathBuf)
}
}
impl<'a> Iterator for SplitPaths<'a> {
type Item = PathBuf;
fn next(&mut self) -> Option<PathBuf> { self.iter.next() }
fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
}
#[derive(Debug)]
pub struct JoinPathsError;
pub fn join_paths<I, T>(paths: I) -> Result<OsString, JoinPathsError>
where I: Iterator<Item=T>, T: AsRef<OsStr>
{
let mut joined = Vec::new();
let sep = b':';
for (i, path) in paths.enumerate() {
let path = path.as_ref().as_bytes();
if i > 0 { joined.push(sep) }
if path.contains(&sep) {
return Err(JoinPathsError)
}
joined.push_all(path);
}
Ok(OsStringExt::from_vec(joined))
}
impl fmt::Display for JoinPathsError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
"path segment contains separator `:`".fmt(f)
}
}
impl StdError for JoinPathsError {
fn description(&self) -> &str { "failed to join paths" }
}
#[cfg(target_os = "freebsd")]
pub fn current_exe() -> io::Result<PathBuf> {
unsafe {
use libc::funcs::bsd44::*;
use libc::consts::os::extra::*;
let mut mib = vec![CTL_KERN as c_int,
KERN_PROC as c_int,
KERN_PROC_PATHNAME as c_int,
-1 as c_int];
let mut sz: libc::size_t = 0;
let err = sysctl(mib.as_mut_ptr(), mib.len() as ::libc::c_uint,
ptr::null_mut(), &mut sz, ptr::null_mut(),
0 as libc::size_t);
if err!= 0 { return Err(io::Error::last_os_error()); }
if sz == 0 { return Err(io::Error::last_os_error()); }
let mut v: Vec<u8> = Vec::with_capacity(sz as usize);
let err = sysctl(mib.as_mut_ptr(), mib.len() as ::libc::c_uint,
v.as_mut_ptr() as *mut libc::c_void, &mut sz,
ptr::null_mut(), 0 as libc::size_t);
if err!= 0 { return Err(io::Error::last_os_error()); }
if sz == 0 { return Err(io::Error::last_os_error()); }
v.set_len(sz as usize - 1); // chop off trailing NUL
Ok(PathBuf::from(OsString::from_vec(v)))
}
}
#[cfg(target_os = "dragonfly")]
pub fn current_exe() -> io::Result<PathBuf> {
::fs::read_link("/proc/curproc/file")
}
#[cfg(any(target_os = "bitrig", target_os = "openbsd"))]
pub fn current_exe() -> io::Result<PathBuf> {
use sync::StaticMutex;
static LOCK: StaticMutex = StaticMutex::new();
extern {
fn rust_current_exe() -> *const c_char;
}
let _guard = LOCK.lock();
unsafe {
let v = rust_current_exe();
if v.is_null() {
Err(io::Error::last_os_error())
} else {
let vec = CStr::from_ptr(v).to_bytes().to_vec();
Ok(PathBuf::from(OsString::from_vec(vec)))
}
}
}
#[cfg(any(target_os = "linux", target_os = "android"))]
pub fn current_exe() -> io::Result<PathBuf> {
::fs::read_link("/proc/self/exe")
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
pub fn current_exe() -> io::Result<PathBuf> {
unsafe {
use libc::funcs::extra::_NSGetExecutablePath;
let mut sz: u32 = 0;
_NSGetExecutablePath(ptr::null_mut(), &mut sz);
if sz == 0 { return Err(io::Error::last_os_error()); }
let mut v: Vec<u8> = Vec::with_capacity(sz as usize);
let err = _NSGetExecutablePath(v.as_mut_ptr() as *mut i8, &mut sz);
if err!= 0 { return Err(io::Error::last_os_error()); }
v.set_len(sz as usize - 1); // chop off trailing NUL
Ok(PathBuf::from(OsString::from_vec(v)))
}
}
pub struct Args {
iter: vec::IntoIter<OsString>,
_dont_send_or_sync_me: *mut (),
}
impl Iterator for Args {
type Item = OsString;
fn next(&mut self) -> Option<OsString> { self.iter.next() }
fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
}
impl ExactSizeIterator for Args {
fn len(&self) -> usize { self.iter.len() }
}
/// Returns the command line arguments
///
/// Returns a list of the command line arguments.
#[cfg(target_os = "macos")]
pub fn args() -> Args {
extern {
// These functions are in crt_externs.h.
fn _NSGetArgc() -> *mut c_int;
fn _NSGetArgv() -> *mut *mut *mut c_char;
}
let vec = unsafe {
let (argc, argv) = (*_NSGetArgc() as isize,
*_NSGetArgv() as *const *const c_char);
(0.. argc as isize).map(|i| {
let bytes = CStr::from_ptr(*argv.offset(i)).to_bytes().to_vec();
OsStringExt::from_vec(bytes)
}).collect::<Vec<_>>()
};
Args {
iter: vec.into_iter(),
_dont_send_or_sync_me: 0 as *mut (),
}
}
// As _NSGetArgc and _NSGetArgv aren't mentioned in iOS docs
// and use underscores in their names - they're most probably
// are considered private and therefore should be avoided
// Here is another way to get arguments using Objective C
// runtime
//
// In general it looks like:
// res = Vec::new()
// let args = [[NSProcessInfo processInfo] arguments]
// for i in (0..[args count])
// res.push([args objectAtIndex:i])
// res
#[cfg(target_os = "ios")]
pub fn args() -> Args {
use mem;
#[link(name = "objc")]
extern {
fn sel_registerName(name: *const libc::c_uchar) -> Sel;
fn objc_msgSend(obj: NsId, sel: Sel,...) -> NsId;
fn objc_getClass(class_name: *const libc::c_uchar) -> NsId;
}
#[link(name = "Foundation", kind = "framework")]
extern {}
type Sel = *const libc::c_void;
type NsId = *const libc::c_void;
let mut res = Vec::new();
unsafe {
let process_info_sel = sel_registerName("processInfo\0".as_ptr());
let arguments_sel = sel_registerName("arguments\0".as_ptr());
let utf8_sel = sel_registerName("UTF8String\0".as_ptr());
let count_sel = sel_registerName("count\0".as_ptr());
let object_at_sel = sel_registerName("objectAtIndex:\0".as_ptr());
let klass = objc_getClass("NSProcessInfo\0".as_ptr());
let info = objc_msgSend(klass, process_info_sel);
let args = objc_msgSend(info, arguments_sel);
let cnt: usize = mem::transmute(objc_msgSend(args, count_sel));
for i in (0..cnt) {
let tmp = objc_msgSend(args, object_at_sel, i);
let utf_c_str: *const libc::c_char =
mem::transmute(objc_msgSend(tmp, utf8_sel));
let bytes = CStr::from_ptr(utf_c_str).to_bytes();
res.push(OsString::from(str::from_utf8(bytes).unwrap()))
}
}
Args { iter: res.into_iter(), _dont_send_or_sync_me: 0 as *mut _ }
}
#[cfg(any(target_os = "linux",
target_os = "android",
target_os = "freebsd",
target_os = "dragonfly",
target_os = "bitrig",
target_os = "openbsd"))]
pub fn args() -> Args {
use rt;
let bytes = rt::args::clone().unwrap_or(Vec::new());
let v: Vec<OsString> = bytes.into_iter().map(|v| {
OsStringExt::from_vec(v)
}).collect();
Args { iter: v.into_iter(), _dont_send_or_sync_me: 0 as *mut _ }
}
pub struct Env {
iter: vec::IntoIter<(OsString, OsString)>,
_dont_send_or_sync_me: *mut (),
}
impl Iterator for Env {
type Item = (OsString, OsString);
fn next(&mut self) -> Option<(OsString, OsString)> { self.iter.next() }
fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
}
#[cfg(target_os = "macos")]
pub unsafe fn environ() -> *mut *const *const c_char {
extern { fn _NSGetEnviron() -> *mut *const *const c_char; }
_NSGetEnviron()
}
#[cfg(not(target_os = "macos"))]
pub unsafe fn environ() -> *mut *const *const c_char {
extern { static mut environ: *const *const c_char; }
&mut environ
}
/// Returns a vector of (variable, value) byte-vector pairs for all the
/// environment variables of the current process.
pub fn env() -> Env {
return unsafe {
let mut environ = *environ();
if environ as usize == 0 {
panic!("os::env() failure getting env string from OS: {}",
io::Error::last_os_error());
}
let mut result = Vec::new();
while *environ!= ptr::null() {
result.push(parse(CStr::from_ptr(*environ).to_bytes()));
environ = environ.offset(1);
}
Env { iter: result.into_iter(), _dont_send_or_sync_me: 0 as *mut _ }
};
fn parse(input: &[u8]) -> (OsString, OsString) {
let mut it = input.splitn(2, |b| *b == b'=');
let key = it.next().unwrap().to_vec();
let default: &[u8] = &[];
let val = it.next().unwrap_or(default).to_vec();
(OsStringExt::from_vec(key), OsStringExt::from_vec(val))
}
}
pub fn getenv(k: &OsStr) -> Option<OsString> {
unsafe {
let s = k.to_cstring().unwrap();
let s = libc::getenv(s.as_ptr()) as *const _;
if s.is_null() {
None
} else {
Some(OsStringExt::from_vec(CStr::from_ptr(s).to_bytes().to_vec()))
}
}
}
pub fn setenv(k: &OsStr, v: &OsStr) {
unsafe {
let k = k.to_cstring().unwrap();
let v = v.to_cstring().unwrap();
if libc::funcs::posix01::unistd::setenv(k.as_ptr(), v.as_ptr(), 1)!= 0 |
}
}
pub fn unsetenv(n: &OsStr) {
unsafe {
let nbuf = n.to_cstring().unwrap();
if libc::funcs::posix01::unistd::unsetenv(nbuf.as_ptr())!= 0 {
panic!("failed unsetenv: {}", io::Error::last_os_error());
}
}
}
pub fn page_size() -> usize {
unsafe {
libc::sysconf(libc::_SC_PAGESIZE) as usize
}
}
pub fn temp_dir() -> PathBuf {
getenv("TMPDIR".as_ref()).map(os2path).unwrap_or_else(|| {
if cfg!(target_os = "android") {
PathBuf::from("/data/local/tmp")
} else {
PathBuf::from("/tmp")
}
})
}
pub fn home_dir() -> Option<PathBuf> {
return getenv("HOME".as_ref()).or_else(|| unsafe {
fallback()
}).map(os2path);
#[cfg(any(target_os = "android",
target_os = "ios"))]
unsafe fn fallback() -> Option<OsString> { None }
#[cfg(not(any(target_os = "android",
target_os = "ios")))]
unsafe fn fallback() -> Option<OsString> {
let amt = match libc::sysconf(c::_SC_GETPW_R_SIZE_MAX) {
n if n < 0 => 512 as usize,
n => n as usize,
};
let me = libc::getuid();
loop {
let mut buf = Vec::with_capacity(amt);
let mut passwd: c::passwd = mem::zeroed();
let mut result = 0 as *mut _;
match c::getpwuid_r(me, &mut passwd, buf.as_mut_ptr(),
buf.capacity() as libc::size_t,
&mut result) {
0 if!result.is_null() => {}
_ => return None
}
let ptr = passwd.pw_dir as *const _;
let bytes = CStr::from_ptr(ptr).to_bytes().to_vec();
return Some(OsStringExt::from_vec(bytes))
}
}
}
pub fn exit(code: i32) ->! {
unsafe { libc::exit(code as c_int) }
}
| {
panic!("failed setenv: {}", io::Error::last_os_error());
} | conditional_block |
os.rs | // 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.
//! Implementation of `std::os` functionality for unix systems
#![allow(unused_imports)] // lots of cfg code here
use prelude::v1::*;
use os::unix::prelude::*;
use error::Error as StdError;
use ffi::{CString, CStr, OsString, OsStr};
use fmt;
use io;
use iter;
use libc::{self, c_int, c_char, c_void};
use mem;
use ptr;
use path::{self, PathBuf};
use slice;
use str;
use sys::c;
use sys::fd;
use vec;
const BUF_BYTES: usize = 2048;
const TMPBUF_SZ: usize = 128;
fn bytes2path(b: &[u8]) -> PathBuf {
PathBuf::from(<OsStr as OsStrExt>::from_bytes(b))
}
fn os2path(os: OsString) -> PathBuf {
bytes2path(os.as_bytes())
}
/// Returns the platform-specific value of errno
pub fn errno() -> i32 {
#[cfg(any(target_os = "macos",
target_os = "ios",
target_os = "freebsd"))]
unsafe fn errno_location() -> *const c_int {
extern { fn __error() -> *const c_int; }
__error()
}
#[cfg(target_os = "bitrig")]
fn errno_location() -> *const c_int {
extern {
fn __errno() -> *const c_int;
}
unsafe {
__errno()
}
}
#[cfg(target_os = "dragonfly")]
unsafe fn errno_location() -> *const c_int {
extern { fn __dfly_error() -> *const c_int; }
__dfly_error()
}
#[cfg(target_os = "openbsd")]
unsafe fn errno_location() -> *const c_int {
extern { fn __errno() -> *const c_int; }
__errno()
}
#[cfg(any(target_os = "linux", target_os = "android"))]
unsafe fn errno_location() -> *const c_int {
extern { fn __errno_location() -> *const c_int; }
__errno_location()
}
unsafe {
(*errno_location()) as i32
}
}
/// Gets a detailed string description for the given error number.
pub fn error_string(errno: i32) -> String {
#[cfg(target_os = "linux")]
extern {
#[link_name = "__xpg_strerror_r"]
fn strerror_r(errnum: c_int, buf: *mut c_char,
buflen: libc::size_t) -> c_int;
}
#[cfg(not(target_os = "linux"))]
extern {
fn strerror_r(errnum: c_int, buf: *mut c_char,
buflen: libc::size_t) -> c_int;
}
let mut buf = [0 as c_char; TMPBUF_SZ];
let p = buf.as_mut_ptr();
unsafe {
if strerror_r(errno as c_int, p, buf.len() as libc::size_t) < 0 {
panic!("strerror_r failure");
}
let p = p as *const _;
str::from_utf8(CStr::from_ptr(p).to_bytes()).unwrap().to_string()
}
}
pub fn getcwd() -> io::Result<PathBuf> {
let mut buf = [0 as c_char; BUF_BYTES];
unsafe {
if libc::getcwd(buf.as_mut_ptr(), buf.len() as libc::size_t).is_null() {
Err(io::Error::last_os_error())
} else {
Ok(bytes2path(CStr::from_ptr(buf.as_ptr()).to_bytes()))
}
}
}
pub fn chdir(p: &path::Path) -> io::Result<()> {
let p: &OsStr = p.as_ref();
let p = try!(CString::new(p.as_bytes()));
unsafe {
match libc::chdir(p.as_ptr()) == (0 as c_int) {
true => Ok(()),
false => Err(io::Error::last_os_error()),
}
}
}
pub struct SplitPaths<'a> {
iter: iter::Map<slice::Split<'a, u8, fn(&u8) -> bool>,
fn(&'a [u8]) -> PathBuf>,
}
pub fn split_paths<'a>(unparsed: &'a OsStr) -> SplitPaths<'a> {
fn is_colon(b: &u8) -> bool { *b == b':' }
let unparsed = unparsed.as_bytes();
SplitPaths {
iter: unparsed.split(is_colon as fn(&u8) -> bool)
.map(bytes2path as fn(&'a [u8]) -> PathBuf)
}
}
impl<'a> Iterator for SplitPaths<'a> {
type Item = PathBuf;
fn next(&mut self) -> Option<PathBuf> { self.iter.next() }
fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
}
#[derive(Debug)]
pub struct JoinPathsError;
pub fn join_paths<I, T>(paths: I) -> Result<OsString, JoinPathsError>
where I: Iterator<Item=T>, T: AsRef<OsStr>
{
let mut joined = Vec::new();
let sep = b':';
for (i, path) in paths.enumerate() {
let path = path.as_ref().as_bytes();
if i > 0 { joined.push(sep) }
if path.contains(&sep) {
return Err(JoinPathsError)
}
joined.push_all(path);
}
Ok(OsStringExt::from_vec(joined))
}
impl fmt::Display for JoinPathsError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
"path segment contains separator `:`".fmt(f)
}
}
impl StdError for JoinPathsError {
fn description(&self) -> &str { "failed to join paths" }
}
#[cfg(target_os = "freebsd")]
pub fn current_exe() -> io::Result<PathBuf> {
unsafe {
use libc::funcs::bsd44::*;
use libc::consts::os::extra::*;
let mut mib = vec![CTL_KERN as c_int,
KERN_PROC as c_int,
KERN_PROC_PATHNAME as c_int,
-1 as c_int];
let mut sz: libc::size_t = 0;
let err = sysctl(mib.as_mut_ptr(), mib.len() as ::libc::c_uint,
ptr::null_mut(), &mut sz, ptr::null_mut(),
0 as libc::size_t);
if err!= 0 { return Err(io::Error::last_os_error()); }
if sz == 0 { return Err(io::Error::last_os_error()); }
let mut v: Vec<u8> = Vec::with_capacity(sz as usize);
let err = sysctl(mib.as_mut_ptr(), mib.len() as ::libc::c_uint,
v.as_mut_ptr() as *mut libc::c_void, &mut sz, | if sz == 0 { return Err(io::Error::last_os_error()); }
v.set_len(sz as usize - 1); // chop off trailing NUL
Ok(PathBuf::from(OsString::from_vec(v)))
}
}
#[cfg(target_os = "dragonfly")]
pub fn current_exe() -> io::Result<PathBuf> {
::fs::read_link("/proc/curproc/file")
}
#[cfg(any(target_os = "bitrig", target_os = "openbsd"))]
pub fn current_exe() -> io::Result<PathBuf> {
use sync::StaticMutex;
static LOCK: StaticMutex = StaticMutex::new();
extern {
fn rust_current_exe() -> *const c_char;
}
let _guard = LOCK.lock();
unsafe {
let v = rust_current_exe();
if v.is_null() {
Err(io::Error::last_os_error())
} else {
let vec = CStr::from_ptr(v).to_bytes().to_vec();
Ok(PathBuf::from(OsString::from_vec(vec)))
}
}
}
#[cfg(any(target_os = "linux", target_os = "android"))]
pub fn current_exe() -> io::Result<PathBuf> {
::fs::read_link("/proc/self/exe")
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
pub fn current_exe() -> io::Result<PathBuf> {
unsafe {
use libc::funcs::extra::_NSGetExecutablePath;
let mut sz: u32 = 0;
_NSGetExecutablePath(ptr::null_mut(), &mut sz);
if sz == 0 { return Err(io::Error::last_os_error()); }
let mut v: Vec<u8> = Vec::with_capacity(sz as usize);
let err = _NSGetExecutablePath(v.as_mut_ptr() as *mut i8, &mut sz);
if err!= 0 { return Err(io::Error::last_os_error()); }
v.set_len(sz as usize - 1); // chop off trailing NUL
Ok(PathBuf::from(OsString::from_vec(v)))
}
}
pub struct Args {
iter: vec::IntoIter<OsString>,
_dont_send_or_sync_me: *mut (),
}
impl Iterator for Args {
type Item = OsString;
fn next(&mut self) -> Option<OsString> { self.iter.next() }
fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
}
impl ExactSizeIterator for Args {
fn len(&self) -> usize { self.iter.len() }
}
/// Returns the command line arguments
///
/// Returns a list of the command line arguments.
#[cfg(target_os = "macos")]
pub fn args() -> Args {
extern {
// These functions are in crt_externs.h.
fn _NSGetArgc() -> *mut c_int;
fn _NSGetArgv() -> *mut *mut *mut c_char;
}
let vec = unsafe {
let (argc, argv) = (*_NSGetArgc() as isize,
*_NSGetArgv() as *const *const c_char);
(0.. argc as isize).map(|i| {
let bytes = CStr::from_ptr(*argv.offset(i)).to_bytes().to_vec();
OsStringExt::from_vec(bytes)
}).collect::<Vec<_>>()
};
Args {
iter: vec.into_iter(),
_dont_send_or_sync_me: 0 as *mut (),
}
}
// As _NSGetArgc and _NSGetArgv aren't mentioned in iOS docs
// and use underscores in their names - they're most probably
// are considered private and therefore should be avoided
// Here is another way to get arguments using Objective C
// runtime
//
// In general it looks like:
// res = Vec::new()
// let args = [[NSProcessInfo processInfo] arguments]
// for i in (0..[args count])
// res.push([args objectAtIndex:i])
// res
#[cfg(target_os = "ios")]
pub fn args() -> Args {
use mem;
#[link(name = "objc")]
extern {
fn sel_registerName(name: *const libc::c_uchar) -> Sel;
fn objc_msgSend(obj: NsId, sel: Sel,...) -> NsId;
fn objc_getClass(class_name: *const libc::c_uchar) -> NsId;
}
#[link(name = "Foundation", kind = "framework")]
extern {}
type Sel = *const libc::c_void;
type NsId = *const libc::c_void;
let mut res = Vec::new();
unsafe {
let process_info_sel = sel_registerName("processInfo\0".as_ptr());
let arguments_sel = sel_registerName("arguments\0".as_ptr());
let utf8_sel = sel_registerName("UTF8String\0".as_ptr());
let count_sel = sel_registerName("count\0".as_ptr());
let object_at_sel = sel_registerName("objectAtIndex:\0".as_ptr());
let klass = objc_getClass("NSProcessInfo\0".as_ptr());
let info = objc_msgSend(klass, process_info_sel);
let args = objc_msgSend(info, arguments_sel);
let cnt: usize = mem::transmute(objc_msgSend(args, count_sel));
for i in (0..cnt) {
let tmp = objc_msgSend(args, object_at_sel, i);
let utf_c_str: *const libc::c_char =
mem::transmute(objc_msgSend(tmp, utf8_sel));
let bytes = CStr::from_ptr(utf_c_str).to_bytes();
res.push(OsString::from(str::from_utf8(bytes).unwrap()))
}
}
Args { iter: res.into_iter(), _dont_send_or_sync_me: 0 as *mut _ }
}
#[cfg(any(target_os = "linux",
target_os = "android",
target_os = "freebsd",
target_os = "dragonfly",
target_os = "bitrig",
target_os = "openbsd"))]
pub fn args() -> Args {
use rt;
let bytes = rt::args::clone().unwrap_or(Vec::new());
let v: Vec<OsString> = bytes.into_iter().map(|v| {
OsStringExt::from_vec(v)
}).collect();
Args { iter: v.into_iter(), _dont_send_or_sync_me: 0 as *mut _ }
}
pub struct Env {
iter: vec::IntoIter<(OsString, OsString)>,
_dont_send_or_sync_me: *mut (),
}
impl Iterator for Env {
type Item = (OsString, OsString);
fn next(&mut self) -> Option<(OsString, OsString)> { self.iter.next() }
fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
}
#[cfg(target_os = "macos")]
pub unsafe fn environ() -> *mut *const *const c_char {
extern { fn _NSGetEnviron() -> *mut *const *const c_char; }
_NSGetEnviron()
}
#[cfg(not(target_os = "macos"))]
pub unsafe fn environ() -> *mut *const *const c_char {
extern { static mut environ: *const *const c_char; }
&mut environ
}
/// Returns a vector of (variable, value) byte-vector pairs for all the
/// environment variables of the current process.
pub fn env() -> Env {
return unsafe {
let mut environ = *environ();
if environ as usize == 0 {
panic!("os::env() failure getting env string from OS: {}",
io::Error::last_os_error());
}
let mut result = Vec::new();
while *environ!= ptr::null() {
result.push(parse(CStr::from_ptr(*environ).to_bytes()));
environ = environ.offset(1);
}
Env { iter: result.into_iter(), _dont_send_or_sync_me: 0 as *mut _ }
};
fn parse(input: &[u8]) -> (OsString, OsString) {
let mut it = input.splitn(2, |b| *b == b'=');
let key = it.next().unwrap().to_vec();
let default: &[u8] = &[];
let val = it.next().unwrap_or(default).to_vec();
(OsStringExt::from_vec(key), OsStringExt::from_vec(val))
}
}
pub fn getenv(k: &OsStr) -> Option<OsString> {
unsafe {
let s = k.to_cstring().unwrap();
let s = libc::getenv(s.as_ptr()) as *const _;
if s.is_null() {
None
} else {
Some(OsStringExt::from_vec(CStr::from_ptr(s).to_bytes().to_vec()))
}
}
}
pub fn setenv(k: &OsStr, v: &OsStr) {
unsafe {
let k = k.to_cstring().unwrap();
let v = v.to_cstring().unwrap();
if libc::funcs::posix01::unistd::setenv(k.as_ptr(), v.as_ptr(), 1)!= 0 {
panic!("failed setenv: {}", io::Error::last_os_error());
}
}
}
pub fn unsetenv(n: &OsStr) {
unsafe {
let nbuf = n.to_cstring().unwrap();
if libc::funcs::posix01::unistd::unsetenv(nbuf.as_ptr())!= 0 {
panic!("failed unsetenv: {}", io::Error::last_os_error());
}
}
}
pub fn page_size() -> usize {
unsafe {
libc::sysconf(libc::_SC_PAGESIZE) as usize
}
}
pub fn temp_dir() -> PathBuf {
getenv("TMPDIR".as_ref()).map(os2path).unwrap_or_else(|| {
if cfg!(target_os = "android") {
PathBuf::from("/data/local/tmp")
} else {
PathBuf::from("/tmp")
}
})
}
pub fn home_dir() -> Option<PathBuf> {
return getenv("HOME".as_ref()).or_else(|| unsafe {
fallback()
}).map(os2path);
#[cfg(any(target_os = "android",
target_os = "ios"))]
unsafe fn fallback() -> Option<OsString> { None }
#[cfg(not(any(target_os = "android",
target_os = "ios")))]
unsafe fn fallback() -> Option<OsString> {
let amt = match libc::sysconf(c::_SC_GETPW_R_SIZE_MAX) {
n if n < 0 => 512 as usize,
n => n as usize,
};
let me = libc::getuid();
loop {
let mut buf = Vec::with_capacity(amt);
let mut passwd: c::passwd = mem::zeroed();
let mut result = 0 as *mut _;
match c::getpwuid_r(me, &mut passwd, buf.as_mut_ptr(),
buf.capacity() as libc::size_t,
&mut result) {
0 if!result.is_null() => {}
_ => return None
}
let ptr = passwd.pw_dir as *const _;
let bytes = CStr::from_ptr(ptr).to_bytes().to_vec();
return Some(OsStringExt::from_vec(bytes))
}
}
}
pub fn exit(code: i32) ->! {
unsafe { libc::exit(code as c_int) }
} | ptr::null_mut(), 0 as libc::size_t);
if err != 0 { return Err(io::Error::last_os_error()); } | random_line_split |
os.rs | // 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.
//! Implementation of `std::os` functionality for unix systems
#![allow(unused_imports)] // lots of cfg code here
use prelude::v1::*;
use os::unix::prelude::*;
use error::Error as StdError;
use ffi::{CString, CStr, OsString, OsStr};
use fmt;
use io;
use iter;
use libc::{self, c_int, c_char, c_void};
use mem;
use ptr;
use path::{self, PathBuf};
use slice;
use str;
use sys::c;
use sys::fd;
use vec;
const BUF_BYTES: usize = 2048;
const TMPBUF_SZ: usize = 128;
fn bytes2path(b: &[u8]) -> PathBuf {
PathBuf::from(<OsStr as OsStrExt>::from_bytes(b))
}
fn os2path(os: OsString) -> PathBuf {
bytes2path(os.as_bytes())
}
/// Returns the platform-specific value of errno
pub fn errno() -> i32 {
#[cfg(any(target_os = "macos",
target_os = "ios",
target_os = "freebsd"))]
unsafe fn errno_location() -> *const c_int {
extern { fn __error() -> *const c_int; }
__error()
}
#[cfg(target_os = "bitrig")]
fn errno_location() -> *const c_int {
extern {
fn __errno() -> *const c_int;
}
unsafe {
__errno()
}
}
#[cfg(target_os = "dragonfly")]
unsafe fn errno_location() -> *const c_int {
extern { fn __dfly_error() -> *const c_int; }
__dfly_error()
}
#[cfg(target_os = "openbsd")]
unsafe fn errno_location() -> *const c_int {
extern { fn __errno() -> *const c_int; }
__errno()
}
#[cfg(any(target_os = "linux", target_os = "android"))]
unsafe fn errno_location() -> *const c_int {
extern { fn __errno_location() -> *const c_int; }
__errno_location()
}
unsafe {
(*errno_location()) as i32
}
}
/// Gets a detailed string description for the given error number.
pub fn error_string(errno: i32) -> String {
#[cfg(target_os = "linux")]
extern {
#[link_name = "__xpg_strerror_r"]
fn strerror_r(errnum: c_int, buf: *mut c_char,
buflen: libc::size_t) -> c_int;
}
#[cfg(not(target_os = "linux"))]
extern {
fn strerror_r(errnum: c_int, buf: *mut c_char,
buflen: libc::size_t) -> c_int;
}
let mut buf = [0 as c_char; TMPBUF_SZ];
let p = buf.as_mut_ptr();
unsafe {
if strerror_r(errno as c_int, p, buf.len() as libc::size_t) < 0 {
panic!("strerror_r failure");
}
let p = p as *const _;
str::from_utf8(CStr::from_ptr(p).to_bytes()).unwrap().to_string()
}
}
pub fn getcwd() -> io::Result<PathBuf> {
let mut buf = [0 as c_char; BUF_BYTES];
unsafe {
if libc::getcwd(buf.as_mut_ptr(), buf.len() as libc::size_t).is_null() {
Err(io::Error::last_os_error())
} else {
Ok(bytes2path(CStr::from_ptr(buf.as_ptr()).to_bytes()))
}
}
}
pub fn chdir(p: &path::Path) -> io::Result<()> {
let p: &OsStr = p.as_ref();
let p = try!(CString::new(p.as_bytes()));
unsafe {
match libc::chdir(p.as_ptr()) == (0 as c_int) {
true => Ok(()),
false => Err(io::Error::last_os_error()),
}
}
}
pub struct SplitPaths<'a> {
iter: iter::Map<slice::Split<'a, u8, fn(&u8) -> bool>,
fn(&'a [u8]) -> PathBuf>,
}
pub fn split_paths<'a>(unparsed: &'a OsStr) -> SplitPaths<'a> {
fn is_colon(b: &u8) -> bool { *b == b':' }
let unparsed = unparsed.as_bytes();
SplitPaths {
iter: unparsed.split(is_colon as fn(&u8) -> bool)
.map(bytes2path as fn(&'a [u8]) -> PathBuf)
}
}
impl<'a> Iterator for SplitPaths<'a> {
type Item = PathBuf;
fn next(&mut self) -> Option<PathBuf> { self.iter.next() }
fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
}
#[derive(Debug)]
pub struct JoinPathsError;
pub fn join_paths<I, T>(paths: I) -> Result<OsString, JoinPathsError>
where I: Iterator<Item=T>, T: AsRef<OsStr>
{
let mut joined = Vec::new();
let sep = b':';
for (i, path) in paths.enumerate() {
let path = path.as_ref().as_bytes();
if i > 0 { joined.push(sep) }
if path.contains(&sep) {
return Err(JoinPathsError)
}
joined.push_all(path);
}
Ok(OsStringExt::from_vec(joined))
}
impl fmt::Display for JoinPathsError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
"path segment contains separator `:`".fmt(f)
}
}
impl StdError for JoinPathsError {
fn description(&self) -> &str { "failed to join paths" }
}
#[cfg(target_os = "freebsd")]
pub fn current_exe() -> io::Result<PathBuf> {
unsafe {
use libc::funcs::bsd44::*;
use libc::consts::os::extra::*;
let mut mib = vec![CTL_KERN as c_int,
KERN_PROC as c_int,
KERN_PROC_PATHNAME as c_int,
-1 as c_int];
let mut sz: libc::size_t = 0;
let err = sysctl(mib.as_mut_ptr(), mib.len() as ::libc::c_uint,
ptr::null_mut(), &mut sz, ptr::null_mut(),
0 as libc::size_t);
if err!= 0 { return Err(io::Error::last_os_error()); }
if sz == 0 { return Err(io::Error::last_os_error()); }
let mut v: Vec<u8> = Vec::with_capacity(sz as usize);
let err = sysctl(mib.as_mut_ptr(), mib.len() as ::libc::c_uint,
v.as_mut_ptr() as *mut libc::c_void, &mut sz,
ptr::null_mut(), 0 as libc::size_t);
if err!= 0 { return Err(io::Error::last_os_error()); }
if sz == 0 { return Err(io::Error::last_os_error()); }
v.set_len(sz as usize - 1); // chop off trailing NUL
Ok(PathBuf::from(OsString::from_vec(v)))
}
}
#[cfg(target_os = "dragonfly")]
pub fn current_exe() -> io::Result<PathBuf> {
::fs::read_link("/proc/curproc/file")
}
#[cfg(any(target_os = "bitrig", target_os = "openbsd"))]
pub fn current_exe() -> io::Result<PathBuf> {
use sync::StaticMutex;
static LOCK: StaticMutex = StaticMutex::new();
extern {
fn rust_current_exe() -> *const c_char;
}
let _guard = LOCK.lock();
unsafe {
let v = rust_current_exe();
if v.is_null() {
Err(io::Error::last_os_error())
} else {
let vec = CStr::from_ptr(v).to_bytes().to_vec();
Ok(PathBuf::from(OsString::from_vec(vec)))
}
}
}
#[cfg(any(target_os = "linux", target_os = "android"))]
pub fn current_exe() -> io::Result<PathBuf> {
::fs::read_link("/proc/self/exe")
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
pub fn current_exe() -> io::Result<PathBuf> {
unsafe {
use libc::funcs::extra::_NSGetExecutablePath;
let mut sz: u32 = 0;
_NSGetExecutablePath(ptr::null_mut(), &mut sz);
if sz == 0 { return Err(io::Error::last_os_error()); }
let mut v: Vec<u8> = Vec::with_capacity(sz as usize);
let err = _NSGetExecutablePath(v.as_mut_ptr() as *mut i8, &mut sz);
if err!= 0 { return Err(io::Error::last_os_error()); }
v.set_len(sz as usize - 1); // chop off trailing NUL
Ok(PathBuf::from(OsString::from_vec(v)))
}
}
pub struct Args {
iter: vec::IntoIter<OsString>,
_dont_send_or_sync_me: *mut (),
}
impl Iterator for Args {
type Item = OsString;
fn next(&mut self) -> Option<OsString> { self.iter.next() }
fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
}
impl ExactSizeIterator for Args {
fn len(&self) -> usize { self.iter.len() }
}
/// Returns the command line arguments
///
/// Returns a list of the command line arguments.
#[cfg(target_os = "macos")]
pub fn args() -> Args {
extern {
// These functions are in crt_externs.h.
fn _NSGetArgc() -> *mut c_int;
fn _NSGetArgv() -> *mut *mut *mut c_char;
}
let vec = unsafe {
let (argc, argv) = (*_NSGetArgc() as isize,
*_NSGetArgv() as *const *const c_char);
(0.. argc as isize).map(|i| {
let bytes = CStr::from_ptr(*argv.offset(i)).to_bytes().to_vec();
OsStringExt::from_vec(bytes)
}).collect::<Vec<_>>()
};
Args {
iter: vec.into_iter(),
_dont_send_or_sync_me: 0 as *mut (),
}
}
// As _NSGetArgc and _NSGetArgv aren't mentioned in iOS docs
// and use underscores in their names - they're most probably
// are considered private and therefore should be avoided
// Here is another way to get arguments using Objective C
// runtime
//
// In general it looks like:
// res = Vec::new()
// let args = [[NSProcessInfo processInfo] arguments]
// for i in (0..[args count])
// res.push([args objectAtIndex:i])
// res
#[cfg(target_os = "ios")]
pub fn args() -> Args {
use mem;
#[link(name = "objc")]
extern {
fn sel_registerName(name: *const libc::c_uchar) -> Sel;
fn objc_msgSend(obj: NsId, sel: Sel,...) -> NsId;
fn objc_getClass(class_name: *const libc::c_uchar) -> NsId;
}
#[link(name = "Foundation", kind = "framework")]
extern {}
type Sel = *const libc::c_void;
type NsId = *const libc::c_void;
let mut res = Vec::new();
unsafe {
let process_info_sel = sel_registerName("processInfo\0".as_ptr());
let arguments_sel = sel_registerName("arguments\0".as_ptr());
let utf8_sel = sel_registerName("UTF8String\0".as_ptr());
let count_sel = sel_registerName("count\0".as_ptr());
let object_at_sel = sel_registerName("objectAtIndex:\0".as_ptr());
let klass = objc_getClass("NSProcessInfo\0".as_ptr());
let info = objc_msgSend(klass, process_info_sel);
let args = objc_msgSend(info, arguments_sel);
let cnt: usize = mem::transmute(objc_msgSend(args, count_sel));
for i in (0..cnt) {
let tmp = objc_msgSend(args, object_at_sel, i);
let utf_c_str: *const libc::c_char =
mem::transmute(objc_msgSend(tmp, utf8_sel));
let bytes = CStr::from_ptr(utf_c_str).to_bytes();
res.push(OsString::from(str::from_utf8(bytes).unwrap()))
}
}
Args { iter: res.into_iter(), _dont_send_or_sync_me: 0 as *mut _ }
}
#[cfg(any(target_os = "linux",
target_os = "android",
target_os = "freebsd",
target_os = "dragonfly",
target_os = "bitrig",
target_os = "openbsd"))]
pub fn args() -> Args {
use rt;
let bytes = rt::args::clone().unwrap_or(Vec::new());
let v: Vec<OsString> = bytes.into_iter().map(|v| {
OsStringExt::from_vec(v)
}).collect();
Args { iter: v.into_iter(), _dont_send_or_sync_me: 0 as *mut _ }
}
pub struct Env {
iter: vec::IntoIter<(OsString, OsString)>,
_dont_send_or_sync_me: *mut (),
}
impl Iterator for Env {
type Item = (OsString, OsString);
fn next(&mut self) -> Option<(OsString, OsString)> { self.iter.next() }
fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
}
#[cfg(target_os = "macos")]
pub unsafe fn environ() -> *mut *const *const c_char {
extern { fn _NSGetEnviron() -> *mut *const *const c_char; }
_NSGetEnviron()
}
#[cfg(not(target_os = "macos"))]
pub unsafe fn environ() -> *mut *const *const c_char {
extern { static mut environ: *const *const c_char; }
&mut environ
}
/// Returns a vector of (variable, value) byte-vector pairs for all the
/// environment variables of the current process.
pub fn env() -> Env {
return unsafe {
let mut environ = *environ();
if environ as usize == 0 {
panic!("os::env() failure getting env string from OS: {}",
io::Error::last_os_error());
}
let mut result = Vec::new();
while *environ!= ptr::null() {
result.push(parse(CStr::from_ptr(*environ).to_bytes()));
environ = environ.offset(1);
}
Env { iter: result.into_iter(), _dont_send_or_sync_me: 0 as *mut _ }
};
fn parse(input: &[u8]) -> (OsString, OsString) {
let mut it = input.splitn(2, |b| *b == b'=');
let key = it.next().unwrap().to_vec();
let default: &[u8] = &[];
let val = it.next().unwrap_or(default).to_vec();
(OsStringExt::from_vec(key), OsStringExt::from_vec(val))
}
}
pub fn getenv(k: &OsStr) -> Option<OsString> {
unsafe {
let s = k.to_cstring().unwrap();
let s = libc::getenv(s.as_ptr()) as *const _;
if s.is_null() {
None
} else {
Some(OsStringExt::from_vec(CStr::from_ptr(s).to_bytes().to_vec()))
}
}
}
pub fn setenv(k: &OsStr, v: &OsStr) {
unsafe {
let k = k.to_cstring().unwrap();
let v = v.to_cstring().unwrap();
if libc::funcs::posix01::unistd::setenv(k.as_ptr(), v.as_ptr(), 1)!= 0 {
panic!("failed setenv: {}", io::Error::last_os_error());
}
}
}
pub fn unsetenv(n: &OsStr) {
unsafe {
let nbuf = n.to_cstring().unwrap();
if libc::funcs::posix01::unistd::unsetenv(nbuf.as_ptr())!= 0 {
panic!("failed unsetenv: {}", io::Error::last_os_error());
}
}
}
pub fn | () -> usize {
unsafe {
libc::sysconf(libc::_SC_PAGESIZE) as usize
}
}
pub fn temp_dir() -> PathBuf {
getenv("TMPDIR".as_ref()).map(os2path).unwrap_or_else(|| {
if cfg!(target_os = "android") {
PathBuf::from("/data/local/tmp")
} else {
PathBuf::from("/tmp")
}
})
}
pub fn home_dir() -> Option<PathBuf> {
return getenv("HOME".as_ref()).or_else(|| unsafe {
fallback()
}).map(os2path);
#[cfg(any(target_os = "android",
target_os = "ios"))]
unsafe fn fallback() -> Option<OsString> { None }
#[cfg(not(any(target_os = "android",
target_os = "ios")))]
unsafe fn fallback() -> Option<OsString> {
let amt = match libc::sysconf(c::_SC_GETPW_R_SIZE_MAX) {
n if n < 0 => 512 as usize,
n => n as usize,
};
let me = libc::getuid();
loop {
let mut buf = Vec::with_capacity(amt);
let mut passwd: c::passwd = mem::zeroed();
let mut result = 0 as *mut _;
match c::getpwuid_r(me, &mut passwd, buf.as_mut_ptr(),
buf.capacity() as libc::size_t,
&mut result) {
0 if!result.is_null() => {}
_ => return None
}
let ptr = passwd.pw_dir as *const _;
let bytes = CStr::from_ptr(ptr).to_bytes().to_vec();
return Some(OsStringExt::from_vec(bytes))
}
}
}
pub fn exit(code: i32) ->! {
unsafe { libc::exit(code as c_int) }
}
| page_size | identifier_name |
os.rs | // 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.
//! Implementation of `std::os` functionality for unix systems
#![allow(unused_imports)] // lots of cfg code here
use prelude::v1::*;
use os::unix::prelude::*;
use error::Error as StdError;
use ffi::{CString, CStr, OsString, OsStr};
use fmt;
use io;
use iter;
use libc::{self, c_int, c_char, c_void};
use mem;
use ptr;
use path::{self, PathBuf};
use slice;
use str;
use sys::c;
use sys::fd;
use vec;
const BUF_BYTES: usize = 2048;
const TMPBUF_SZ: usize = 128;
fn bytes2path(b: &[u8]) -> PathBuf {
PathBuf::from(<OsStr as OsStrExt>::from_bytes(b))
}
fn os2path(os: OsString) -> PathBuf {
bytes2path(os.as_bytes())
}
/// Returns the platform-specific value of errno
pub fn errno() -> i32 {
#[cfg(any(target_os = "macos",
target_os = "ios",
target_os = "freebsd"))]
unsafe fn errno_location() -> *const c_int {
extern { fn __error() -> *const c_int; }
__error()
}
#[cfg(target_os = "bitrig")]
fn errno_location() -> *const c_int {
extern {
fn __errno() -> *const c_int;
}
unsafe {
__errno()
}
}
#[cfg(target_os = "dragonfly")]
unsafe fn errno_location() -> *const c_int {
extern { fn __dfly_error() -> *const c_int; }
__dfly_error()
}
#[cfg(target_os = "openbsd")]
unsafe fn errno_location() -> *const c_int {
extern { fn __errno() -> *const c_int; }
__errno()
}
#[cfg(any(target_os = "linux", target_os = "android"))]
unsafe fn errno_location() -> *const c_int {
extern { fn __errno_location() -> *const c_int; }
__errno_location()
}
unsafe {
(*errno_location()) as i32
}
}
/// Gets a detailed string description for the given error number.
pub fn error_string(errno: i32) -> String {
#[cfg(target_os = "linux")]
extern {
#[link_name = "__xpg_strerror_r"]
fn strerror_r(errnum: c_int, buf: *mut c_char,
buflen: libc::size_t) -> c_int;
}
#[cfg(not(target_os = "linux"))]
extern {
fn strerror_r(errnum: c_int, buf: *mut c_char,
buflen: libc::size_t) -> c_int;
}
let mut buf = [0 as c_char; TMPBUF_SZ];
let p = buf.as_mut_ptr();
unsafe {
if strerror_r(errno as c_int, p, buf.len() as libc::size_t) < 0 {
panic!("strerror_r failure");
}
let p = p as *const _;
str::from_utf8(CStr::from_ptr(p).to_bytes()).unwrap().to_string()
}
}
pub fn getcwd() -> io::Result<PathBuf> {
let mut buf = [0 as c_char; BUF_BYTES];
unsafe {
if libc::getcwd(buf.as_mut_ptr(), buf.len() as libc::size_t).is_null() {
Err(io::Error::last_os_error())
} else {
Ok(bytes2path(CStr::from_ptr(buf.as_ptr()).to_bytes()))
}
}
}
pub fn chdir(p: &path::Path) -> io::Result<()> {
let p: &OsStr = p.as_ref();
let p = try!(CString::new(p.as_bytes()));
unsafe {
match libc::chdir(p.as_ptr()) == (0 as c_int) {
true => Ok(()),
false => Err(io::Error::last_os_error()),
}
}
}
pub struct SplitPaths<'a> {
iter: iter::Map<slice::Split<'a, u8, fn(&u8) -> bool>,
fn(&'a [u8]) -> PathBuf>,
}
pub fn split_paths<'a>(unparsed: &'a OsStr) -> SplitPaths<'a> {
fn is_colon(b: &u8) -> bool { *b == b':' }
let unparsed = unparsed.as_bytes();
SplitPaths {
iter: unparsed.split(is_colon as fn(&u8) -> bool)
.map(bytes2path as fn(&'a [u8]) -> PathBuf)
}
}
impl<'a> Iterator for SplitPaths<'a> {
type Item = PathBuf;
fn next(&mut self) -> Option<PathBuf> |
fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
}
#[derive(Debug)]
pub struct JoinPathsError;
pub fn join_paths<I, T>(paths: I) -> Result<OsString, JoinPathsError>
where I: Iterator<Item=T>, T: AsRef<OsStr>
{
let mut joined = Vec::new();
let sep = b':';
for (i, path) in paths.enumerate() {
let path = path.as_ref().as_bytes();
if i > 0 { joined.push(sep) }
if path.contains(&sep) {
return Err(JoinPathsError)
}
joined.push_all(path);
}
Ok(OsStringExt::from_vec(joined))
}
impl fmt::Display for JoinPathsError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
"path segment contains separator `:`".fmt(f)
}
}
impl StdError for JoinPathsError {
fn description(&self) -> &str { "failed to join paths" }
}
#[cfg(target_os = "freebsd")]
pub fn current_exe() -> io::Result<PathBuf> {
unsafe {
use libc::funcs::bsd44::*;
use libc::consts::os::extra::*;
let mut mib = vec![CTL_KERN as c_int,
KERN_PROC as c_int,
KERN_PROC_PATHNAME as c_int,
-1 as c_int];
let mut sz: libc::size_t = 0;
let err = sysctl(mib.as_mut_ptr(), mib.len() as ::libc::c_uint,
ptr::null_mut(), &mut sz, ptr::null_mut(),
0 as libc::size_t);
if err!= 0 { return Err(io::Error::last_os_error()); }
if sz == 0 { return Err(io::Error::last_os_error()); }
let mut v: Vec<u8> = Vec::with_capacity(sz as usize);
let err = sysctl(mib.as_mut_ptr(), mib.len() as ::libc::c_uint,
v.as_mut_ptr() as *mut libc::c_void, &mut sz,
ptr::null_mut(), 0 as libc::size_t);
if err!= 0 { return Err(io::Error::last_os_error()); }
if sz == 0 { return Err(io::Error::last_os_error()); }
v.set_len(sz as usize - 1); // chop off trailing NUL
Ok(PathBuf::from(OsString::from_vec(v)))
}
}
#[cfg(target_os = "dragonfly")]
pub fn current_exe() -> io::Result<PathBuf> {
::fs::read_link("/proc/curproc/file")
}
#[cfg(any(target_os = "bitrig", target_os = "openbsd"))]
pub fn current_exe() -> io::Result<PathBuf> {
use sync::StaticMutex;
static LOCK: StaticMutex = StaticMutex::new();
extern {
fn rust_current_exe() -> *const c_char;
}
let _guard = LOCK.lock();
unsafe {
let v = rust_current_exe();
if v.is_null() {
Err(io::Error::last_os_error())
} else {
let vec = CStr::from_ptr(v).to_bytes().to_vec();
Ok(PathBuf::from(OsString::from_vec(vec)))
}
}
}
#[cfg(any(target_os = "linux", target_os = "android"))]
pub fn current_exe() -> io::Result<PathBuf> {
::fs::read_link("/proc/self/exe")
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
pub fn current_exe() -> io::Result<PathBuf> {
unsafe {
use libc::funcs::extra::_NSGetExecutablePath;
let mut sz: u32 = 0;
_NSGetExecutablePath(ptr::null_mut(), &mut sz);
if sz == 0 { return Err(io::Error::last_os_error()); }
let mut v: Vec<u8> = Vec::with_capacity(sz as usize);
let err = _NSGetExecutablePath(v.as_mut_ptr() as *mut i8, &mut sz);
if err!= 0 { return Err(io::Error::last_os_error()); }
v.set_len(sz as usize - 1); // chop off trailing NUL
Ok(PathBuf::from(OsString::from_vec(v)))
}
}
pub struct Args {
iter: vec::IntoIter<OsString>,
_dont_send_or_sync_me: *mut (),
}
impl Iterator for Args {
type Item = OsString;
fn next(&mut self) -> Option<OsString> { self.iter.next() }
fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
}
impl ExactSizeIterator for Args {
fn len(&self) -> usize { self.iter.len() }
}
/// Returns the command line arguments
///
/// Returns a list of the command line arguments.
#[cfg(target_os = "macos")]
pub fn args() -> Args {
extern {
// These functions are in crt_externs.h.
fn _NSGetArgc() -> *mut c_int;
fn _NSGetArgv() -> *mut *mut *mut c_char;
}
let vec = unsafe {
let (argc, argv) = (*_NSGetArgc() as isize,
*_NSGetArgv() as *const *const c_char);
(0.. argc as isize).map(|i| {
let bytes = CStr::from_ptr(*argv.offset(i)).to_bytes().to_vec();
OsStringExt::from_vec(bytes)
}).collect::<Vec<_>>()
};
Args {
iter: vec.into_iter(),
_dont_send_or_sync_me: 0 as *mut (),
}
}
// As _NSGetArgc and _NSGetArgv aren't mentioned in iOS docs
// and use underscores in their names - they're most probably
// are considered private and therefore should be avoided
// Here is another way to get arguments using Objective C
// runtime
//
// In general it looks like:
// res = Vec::new()
// let args = [[NSProcessInfo processInfo] arguments]
// for i in (0..[args count])
// res.push([args objectAtIndex:i])
// res
#[cfg(target_os = "ios")]
pub fn args() -> Args {
use mem;
#[link(name = "objc")]
extern {
fn sel_registerName(name: *const libc::c_uchar) -> Sel;
fn objc_msgSend(obj: NsId, sel: Sel,...) -> NsId;
fn objc_getClass(class_name: *const libc::c_uchar) -> NsId;
}
#[link(name = "Foundation", kind = "framework")]
extern {}
type Sel = *const libc::c_void;
type NsId = *const libc::c_void;
let mut res = Vec::new();
unsafe {
let process_info_sel = sel_registerName("processInfo\0".as_ptr());
let arguments_sel = sel_registerName("arguments\0".as_ptr());
let utf8_sel = sel_registerName("UTF8String\0".as_ptr());
let count_sel = sel_registerName("count\0".as_ptr());
let object_at_sel = sel_registerName("objectAtIndex:\0".as_ptr());
let klass = objc_getClass("NSProcessInfo\0".as_ptr());
let info = objc_msgSend(klass, process_info_sel);
let args = objc_msgSend(info, arguments_sel);
let cnt: usize = mem::transmute(objc_msgSend(args, count_sel));
for i in (0..cnt) {
let tmp = objc_msgSend(args, object_at_sel, i);
let utf_c_str: *const libc::c_char =
mem::transmute(objc_msgSend(tmp, utf8_sel));
let bytes = CStr::from_ptr(utf_c_str).to_bytes();
res.push(OsString::from(str::from_utf8(bytes).unwrap()))
}
}
Args { iter: res.into_iter(), _dont_send_or_sync_me: 0 as *mut _ }
}
#[cfg(any(target_os = "linux",
target_os = "android",
target_os = "freebsd",
target_os = "dragonfly",
target_os = "bitrig",
target_os = "openbsd"))]
pub fn args() -> Args {
use rt;
let bytes = rt::args::clone().unwrap_or(Vec::new());
let v: Vec<OsString> = bytes.into_iter().map(|v| {
OsStringExt::from_vec(v)
}).collect();
Args { iter: v.into_iter(), _dont_send_or_sync_me: 0 as *mut _ }
}
pub struct Env {
iter: vec::IntoIter<(OsString, OsString)>,
_dont_send_or_sync_me: *mut (),
}
impl Iterator for Env {
type Item = (OsString, OsString);
fn next(&mut self) -> Option<(OsString, OsString)> { self.iter.next() }
fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
}
#[cfg(target_os = "macos")]
pub unsafe fn environ() -> *mut *const *const c_char {
extern { fn _NSGetEnviron() -> *mut *const *const c_char; }
_NSGetEnviron()
}
#[cfg(not(target_os = "macos"))]
pub unsafe fn environ() -> *mut *const *const c_char {
extern { static mut environ: *const *const c_char; }
&mut environ
}
/// Returns a vector of (variable, value) byte-vector pairs for all the
/// environment variables of the current process.
pub fn env() -> Env {
return unsafe {
let mut environ = *environ();
if environ as usize == 0 {
panic!("os::env() failure getting env string from OS: {}",
io::Error::last_os_error());
}
let mut result = Vec::new();
while *environ!= ptr::null() {
result.push(parse(CStr::from_ptr(*environ).to_bytes()));
environ = environ.offset(1);
}
Env { iter: result.into_iter(), _dont_send_or_sync_me: 0 as *mut _ }
};
fn parse(input: &[u8]) -> (OsString, OsString) {
let mut it = input.splitn(2, |b| *b == b'=');
let key = it.next().unwrap().to_vec();
let default: &[u8] = &[];
let val = it.next().unwrap_or(default).to_vec();
(OsStringExt::from_vec(key), OsStringExt::from_vec(val))
}
}
pub fn getenv(k: &OsStr) -> Option<OsString> {
unsafe {
let s = k.to_cstring().unwrap();
let s = libc::getenv(s.as_ptr()) as *const _;
if s.is_null() {
None
} else {
Some(OsStringExt::from_vec(CStr::from_ptr(s).to_bytes().to_vec()))
}
}
}
pub fn setenv(k: &OsStr, v: &OsStr) {
unsafe {
let k = k.to_cstring().unwrap();
let v = v.to_cstring().unwrap();
if libc::funcs::posix01::unistd::setenv(k.as_ptr(), v.as_ptr(), 1)!= 0 {
panic!("failed setenv: {}", io::Error::last_os_error());
}
}
}
pub fn unsetenv(n: &OsStr) {
unsafe {
let nbuf = n.to_cstring().unwrap();
if libc::funcs::posix01::unistd::unsetenv(nbuf.as_ptr())!= 0 {
panic!("failed unsetenv: {}", io::Error::last_os_error());
}
}
}
pub fn page_size() -> usize {
unsafe {
libc::sysconf(libc::_SC_PAGESIZE) as usize
}
}
pub fn temp_dir() -> PathBuf {
getenv("TMPDIR".as_ref()).map(os2path).unwrap_or_else(|| {
if cfg!(target_os = "android") {
PathBuf::from("/data/local/tmp")
} else {
PathBuf::from("/tmp")
}
})
}
pub fn home_dir() -> Option<PathBuf> {
return getenv("HOME".as_ref()).or_else(|| unsafe {
fallback()
}).map(os2path);
#[cfg(any(target_os = "android",
target_os = "ios"))]
unsafe fn fallback() -> Option<OsString> { None }
#[cfg(not(any(target_os = "android",
target_os = "ios")))]
unsafe fn fallback() -> Option<OsString> {
let amt = match libc::sysconf(c::_SC_GETPW_R_SIZE_MAX) {
n if n < 0 => 512 as usize,
n => n as usize,
};
let me = libc::getuid();
loop {
let mut buf = Vec::with_capacity(amt);
let mut passwd: c::passwd = mem::zeroed();
let mut result = 0 as *mut _;
match c::getpwuid_r(me, &mut passwd, buf.as_mut_ptr(),
buf.capacity() as libc::size_t,
&mut result) {
0 if!result.is_null() => {}
_ => return None
}
let ptr = passwd.pw_dir as *const _;
let bytes = CStr::from_ptr(ptr).to_bytes().to_vec();
return Some(OsStringExt::from_vec(bytes))
}
}
}
pub fn exit(code: i32) ->! {
unsafe { libc::exit(code as c_int) }
}
| { self.iter.next() } | identifier_body |
dst-dtor-2.rs | // 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.
#![feature(box_syntax)]
static mut DROP_RAN: int = 0;
struct Foo;
impl Drop for Foo {
fn | (&mut self) {
unsafe { DROP_RAN += 1; }
}
}
struct Fat<T:?Sized> {
f: T
}
pub fn main() {
{
let _x: Box<Fat<[Foo]>> = box Fat { f: [Foo, Foo, Foo] };
}
unsafe {
assert!(DROP_RAN == 3);
}
}
| drop | identifier_name |
dst-dtor-2.rs | // 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.
#![feature(box_syntax)]
static mut DROP_RAN: int = 0;
struct Foo;
impl Drop for Foo {
fn drop(&mut self) {
unsafe { DROP_RAN += 1; }
}
}
struct Fat<T:?Sized> {
f: T
}
pub fn main() { | let _x: Box<Fat<[Foo]>> = box Fat { f: [Foo, Foo, Foo] };
}
unsafe {
assert!(DROP_RAN == 3);
}
} | { | random_line_split |
dst-dtor-2.rs | // 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.
#![feature(box_syntax)]
static mut DROP_RAN: int = 0;
struct Foo;
impl Drop for Foo {
fn drop(&mut self) {
unsafe { DROP_RAN += 1; }
}
}
struct Fat<T:?Sized> {
f: T
}
pub fn main() | {
{
let _x: Box<Fat<[Foo]>> = box Fat { f: [Foo, Foo, Foo] };
}
unsafe {
assert!(DROP_RAN == 3);
}
} | identifier_body | |
issue-410.rs | #![allow(
dead_code,
non_snake_case,
non_camel_case_types,
non_upper_case_globals
)]
#[allow(non_snake_case, non_camel_case_types, non_upper_case_globals)]
pub mod root {
#[allow(unused_imports)]
use self::super::root;
pub mod JS {
#[allow(unused_imports)]
use self::super::super::root;
#[repr(C)]
#[derive(Debug, Default, Copy, Clone)]
pub struct | {
pub _address: u8,
}
#[test]
fn bindgen_test_layout_Value() {
assert_eq!(
::std::mem::size_of::<Value>(),
1usize,
concat!("Size of: ", stringify!(Value))
);
assert_eq!(
::std::mem::align_of::<Value>(),
1usize,
concat!("Alignment of ", stringify!(Value))
);
}
extern "C" {
#[link_name = "\u{1}_ZN2JS5Value1aE10JSWhyMagic"]
pub fn Value_a(this: *mut root::JS::Value, arg1: root::JSWhyMagic);
}
impl Value {
#[inline]
pub unsafe fn a(&mut self, arg1: root::JSWhyMagic) {
Value_a(self, arg1)
}
}
}
#[repr(u32)]
#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
pub enum JSWhyMagic {
__bindgen_cannot_repr_c_on_empty_enum = 0,
}
}
| Value | identifier_name |
issue-410.rs | #![allow(
dead_code,
non_snake_case,
non_camel_case_types,
non_upper_case_globals
)]
#[allow(non_snake_case, non_camel_case_types, non_upper_case_globals)]
pub mod root {
#[allow(unused_imports)]
use self::super::root;
pub mod JS {
#[allow(unused_imports)]
use self::super::super::root;
#[repr(C)]
#[derive(Debug, Default, Copy, Clone)]
pub struct Value {
pub _address: u8,
}
#[test]
fn bindgen_test_layout_Value() {
assert_eq!(
::std::mem::size_of::<Value>(),
1usize,
concat!("Size of: ", stringify!(Value))
); | 1usize,
concat!("Alignment of ", stringify!(Value))
);
}
extern "C" {
#[link_name = "\u{1}_ZN2JS5Value1aE10JSWhyMagic"]
pub fn Value_a(this: *mut root::JS::Value, arg1: root::JSWhyMagic);
}
impl Value {
#[inline]
pub unsafe fn a(&mut self, arg1: root::JSWhyMagic) {
Value_a(self, arg1)
}
}
}
#[repr(u32)]
#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
pub enum JSWhyMagic {
__bindgen_cannot_repr_c_on_empty_enum = 0,
}
} | assert_eq!(
::std::mem::align_of::<Value>(), | random_line_split |
handshake.rs | // Copyright 2016 The Grin Developers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::collections::VecDeque;
use std::net::SocketAddr;
use std::sync::{Arc, RwLock};
use futures::Future;
use rand::Rng;
use rand::os::OsRng;
use tokio_core::net::TcpStream;
use core::core::target::Difficulty;
use core::ser;
use msg::*;
use types::*;
use protocol::ProtocolV1;
const NONCES_CAP: usize = 100;
/// Handles the handshake negotiation when two peers connect and decides on
/// protocol.
pub struct Handshake {
/// Ring buffer of nonces sent to detect self connections without requiring
/// a node id.
nonces: Arc<RwLock<VecDeque<u64>>>,
}
unsafe impl Sync for Handshake {}
unsafe impl Send for Handshake {}
impl Handshake {
/// Creates a new handshake handler
pub fn new() -> Handshake {
Handshake { nonces: Arc::new(RwLock::new(VecDeque::with_capacity(NONCES_CAP))) }
}
/// Handles connecting to a new remote peer, starting the version handshake.
pub fn connect(&self,
capab: Capabilities,
total_difficulty: Difficulty,
self_addr: SocketAddr,
conn: TcpStream)
-> Box<Future<Item = (TcpStream, ProtocolV1, PeerInfo), Error = Error>> {
// prepare the first part of the hanshake
let nonce = self.next_nonce();
let hand = Hand {
version: PROTOCOL_VERSION,
capabilities: capab,
nonce: nonce,
total_difficulty: total_difficulty,
sender_addr: SockAddr(self_addr),
receiver_addr: SockAddr(conn.peer_addr().unwrap()),
user_agent: USER_AGENT.to_string(),
};
// write and read the handshake response
Box::new(write_msg(conn, hand, Type::Hand)
.and_then(|conn| read_msg::<Shake>(conn))
.and_then(|(conn, shake)| {
if shake.version!= 1 {
Err(Error::Serialization(ser::Error::UnexpectedData {
expected: vec![PROTOCOL_VERSION as u8],
received: vec![shake.version as u8],
}))
} else {
let peer_info = PeerInfo {
capabilities: shake.capabilities,
user_agent: shake.user_agent,
addr: conn.peer_addr().unwrap(),
version: shake.version,
total_difficulty: shake.total_difficulty,
};
info!("Connected to peer {:?}", peer_info);
// when more than one protocol version is supported, choosing should go here
Ok((conn, ProtocolV1::new(), peer_info))
}
}))
}
/// Handles receiving a connection from a new remote peer that started the
/// version handshake.
pub fn handshake(&self,
capab: Capabilities,
total_difficulty: Difficulty,
conn: TcpStream)
-> Box<Future<Item = (TcpStream, ProtocolV1, PeerInfo), Error = Error>> | // all good, keep peer info
let peer_info = PeerInfo {
capabilities: hand.capabilities,
user_agent: hand.user_agent,
addr: hand.sender_addr.0,
version: hand.version,
total_difficulty: hand.total_difficulty,
};
// send our reply with our info
let shake = Shake {
version: PROTOCOL_VERSION,
capabilities: capab,
total_difficulty: total_difficulty,
user_agent: USER_AGENT.to_string(),
};
Ok((conn, shake, peer_info))
})
.and_then(|(conn, shake, peer_info)| {
debug!("Success handshake with {}.", peer_info.addr);
write_msg(conn, shake, Type::Shake)
// when more than one protocol version is supported, choosing should go here
.map(|conn| (conn, ProtocolV1::new(), peer_info))
}))
}
/// Generate a new random nonce and store it in our ring buffer
fn next_nonce(&self) -> u64 {
let mut rng = OsRng::new().unwrap();
let nonce = rng.next_u64();
let mut nonces = self.nonces.write().unwrap();
nonces.push_back(nonce);
if nonces.len() >= NONCES_CAP {
nonces.pop_front();
}
nonce
}
}
| {
let nonces = self.nonces.clone();
Box::new(read_msg::<Hand>(conn)
.and_then(move |(conn, hand)| {
if hand.version != 1 {
return Err(Error::Serialization(ser::Error::UnexpectedData {
expected: vec![PROTOCOL_VERSION as u8],
received: vec![hand.version as u8],
}));
}
{
// check the nonce to see if we could be trying to connect to ourselves
let nonces = nonces.read().unwrap();
if nonces.contains(&hand.nonce) {
return Err(Error::Serialization(ser::Error::UnexpectedData {
expected: vec![],
received: vec![],
}));
}
} | identifier_body |
handshake.rs | // You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::collections::VecDeque;
use std::net::SocketAddr;
use std::sync::{Arc, RwLock};
use futures::Future;
use rand::Rng;
use rand::os::OsRng;
use tokio_core::net::TcpStream;
use core::core::target::Difficulty;
use core::ser;
use msg::*;
use types::*;
use protocol::ProtocolV1;
const NONCES_CAP: usize = 100;
/// Handles the handshake negotiation when two peers connect and decides on
/// protocol.
pub struct Handshake {
/// Ring buffer of nonces sent to detect self connections without requiring
/// a node id.
nonces: Arc<RwLock<VecDeque<u64>>>,
}
unsafe impl Sync for Handshake {}
unsafe impl Send for Handshake {}
impl Handshake {
/// Creates a new handshake handler
pub fn new() -> Handshake {
Handshake { nonces: Arc::new(RwLock::new(VecDeque::with_capacity(NONCES_CAP))) }
}
/// Handles connecting to a new remote peer, starting the version handshake.
pub fn connect(&self,
capab: Capabilities,
total_difficulty: Difficulty,
self_addr: SocketAddr,
conn: TcpStream)
-> Box<Future<Item = (TcpStream, ProtocolV1, PeerInfo), Error = Error>> {
// prepare the first part of the hanshake
let nonce = self.next_nonce();
let hand = Hand {
version: PROTOCOL_VERSION,
capabilities: capab,
nonce: nonce,
total_difficulty: total_difficulty,
sender_addr: SockAddr(self_addr),
receiver_addr: SockAddr(conn.peer_addr().unwrap()),
user_agent: USER_AGENT.to_string(),
};
// write and read the handshake response
Box::new(write_msg(conn, hand, Type::Hand)
.and_then(|conn| read_msg::<Shake>(conn))
.and_then(|(conn, shake)| {
if shake.version!= 1 {
Err(Error::Serialization(ser::Error::UnexpectedData {
expected: vec![PROTOCOL_VERSION as u8],
received: vec![shake.version as u8],
}))
} else {
let peer_info = PeerInfo {
capabilities: shake.capabilities,
user_agent: shake.user_agent,
addr: conn.peer_addr().unwrap(),
version: shake.version,
total_difficulty: shake.total_difficulty,
};
info!("Connected to peer {:?}", peer_info);
// when more than one protocol version is supported, choosing should go here
Ok((conn, ProtocolV1::new(), peer_info))
}
}))
}
/// Handles receiving a connection from a new remote peer that started the
/// version handshake.
pub fn handshake(&self,
capab: Capabilities,
total_difficulty: Difficulty,
conn: TcpStream)
-> Box<Future<Item = (TcpStream, ProtocolV1, PeerInfo), Error = Error>> {
let nonces = self.nonces.clone();
Box::new(read_msg::<Hand>(conn)
.and_then(move |(conn, hand)| {
if hand.version!= 1 {
return Err(Error::Serialization(ser::Error::UnexpectedData {
expected: vec![PROTOCOL_VERSION as u8],
received: vec![hand.version as u8],
}));
}
{
// check the nonce to see if we could be trying to connect to ourselves
let nonces = nonces.read().unwrap();
if nonces.contains(&hand.nonce) {
return Err(Error::Serialization(ser::Error::UnexpectedData {
expected: vec![],
received: vec![],
}));
}
}
// all good, keep peer info
let peer_info = PeerInfo {
capabilities: hand.capabilities,
user_agent: hand.user_agent,
addr: hand.sender_addr.0,
version: hand.version,
total_difficulty: hand.total_difficulty,
};
// send our reply with our info
let shake = Shake {
version: PROTOCOL_VERSION,
capabilities: capab,
total_difficulty: total_difficulty,
user_agent: USER_AGENT.to_string(),
};
Ok((conn, shake, peer_info))
})
.and_then(|(conn, shake, peer_info)| {
debug!("Success handshake with {}.", peer_info.addr);
write_msg(conn, shake, Type::Shake)
// when more than one protocol version is supported, choosing should go here
.map(|conn| (conn, ProtocolV1::new(), peer_info))
}))
}
/// Generate a new random nonce and store it in our ring buffer
fn next_nonce(&self) -> u64 {
let mut rng = OsRng::new().unwrap();
let nonce = rng.next_u64();
let mut nonces = self.nonces.write().unwrap();
nonces.push_back(nonce);
if nonces.len() >= NONCES_CAP {
nonces.pop_front();
}
nonce
}
} | // Copyright 2016 The Grin Developers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License. | random_line_split | |
handshake.rs | // Copyright 2016 The Grin Developers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::collections::VecDeque;
use std::net::SocketAddr;
use std::sync::{Arc, RwLock};
use futures::Future;
use rand::Rng;
use rand::os::OsRng;
use tokio_core::net::TcpStream;
use core::core::target::Difficulty;
use core::ser;
use msg::*;
use types::*;
use protocol::ProtocolV1;
const NONCES_CAP: usize = 100;
/// Handles the handshake negotiation when two peers connect and decides on
/// protocol.
pub struct Handshake {
/// Ring buffer of nonces sent to detect self connections without requiring
/// a node id.
nonces: Arc<RwLock<VecDeque<u64>>>,
}
unsafe impl Sync for Handshake {}
unsafe impl Send for Handshake {}
impl Handshake {
/// Creates a new handshake handler
pub fn new() -> Handshake {
Handshake { nonces: Arc::new(RwLock::new(VecDeque::with_capacity(NONCES_CAP))) }
}
/// Handles connecting to a new remote peer, starting the version handshake.
pub fn connect(&self,
capab: Capabilities,
total_difficulty: Difficulty,
self_addr: SocketAddr,
conn: TcpStream)
-> Box<Future<Item = (TcpStream, ProtocolV1, PeerInfo), Error = Error>> {
// prepare the first part of the hanshake
let nonce = self.next_nonce();
let hand = Hand {
version: PROTOCOL_VERSION,
capabilities: capab,
nonce: nonce,
total_difficulty: total_difficulty,
sender_addr: SockAddr(self_addr),
receiver_addr: SockAddr(conn.peer_addr().unwrap()),
user_agent: USER_AGENT.to_string(),
};
// write and read the handshake response
Box::new(write_msg(conn, hand, Type::Hand)
.and_then(|conn| read_msg::<Shake>(conn))
.and_then(|(conn, shake)| {
if shake.version!= 1 {
Err(Error::Serialization(ser::Error::UnexpectedData {
expected: vec![PROTOCOL_VERSION as u8],
received: vec![shake.version as u8],
}))
} else {
let peer_info = PeerInfo {
capabilities: shake.capabilities,
user_agent: shake.user_agent,
addr: conn.peer_addr().unwrap(),
version: shake.version,
total_difficulty: shake.total_difficulty,
};
info!("Connected to peer {:?}", peer_info);
// when more than one protocol version is supported, choosing should go here
Ok((conn, ProtocolV1::new(), peer_info))
}
}))
}
/// Handles receiving a connection from a new remote peer that started the
/// version handshake.
pub fn | (&self,
capab: Capabilities,
total_difficulty: Difficulty,
conn: TcpStream)
-> Box<Future<Item = (TcpStream, ProtocolV1, PeerInfo), Error = Error>> {
let nonces = self.nonces.clone();
Box::new(read_msg::<Hand>(conn)
.and_then(move |(conn, hand)| {
if hand.version!= 1 {
return Err(Error::Serialization(ser::Error::UnexpectedData {
expected: vec![PROTOCOL_VERSION as u8],
received: vec![hand.version as u8],
}));
}
{
// check the nonce to see if we could be trying to connect to ourselves
let nonces = nonces.read().unwrap();
if nonces.contains(&hand.nonce) {
return Err(Error::Serialization(ser::Error::UnexpectedData {
expected: vec![],
received: vec![],
}));
}
}
// all good, keep peer info
let peer_info = PeerInfo {
capabilities: hand.capabilities,
user_agent: hand.user_agent,
addr: hand.sender_addr.0,
version: hand.version,
total_difficulty: hand.total_difficulty,
};
// send our reply with our info
let shake = Shake {
version: PROTOCOL_VERSION,
capabilities: capab,
total_difficulty: total_difficulty,
user_agent: USER_AGENT.to_string(),
};
Ok((conn, shake, peer_info))
})
.and_then(|(conn, shake, peer_info)| {
debug!("Success handshake with {}.", peer_info.addr);
write_msg(conn, shake, Type::Shake)
// when more than one protocol version is supported, choosing should go here
.map(|conn| (conn, ProtocolV1::new(), peer_info))
}))
}
/// Generate a new random nonce and store it in our ring buffer
fn next_nonce(&self) -> u64 {
let mut rng = OsRng::new().unwrap();
let nonce = rng.next_u64();
let mut nonces = self.nonces.write().unwrap();
nonces.push_back(nonce);
if nonces.len() >= NONCES_CAP {
nonces.pop_front();
}
nonce
}
}
| handshake | identifier_name |
handshake.rs | // Copyright 2016 The Grin Developers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::collections::VecDeque;
use std::net::SocketAddr;
use std::sync::{Arc, RwLock};
use futures::Future;
use rand::Rng;
use rand::os::OsRng;
use tokio_core::net::TcpStream;
use core::core::target::Difficulty;
use core::ser;
use msg::*;
use types::*;
use protocol::ProtocolV1;
const NONCES_CAP: usize = 100;
/// Handles the handshake negotiation when two peers connect and decides on
/// protocol.
pub struct Handshake {
/// Ring buffer of nonces sent to detect self connections without requiring
/// a node id.
nonces: Arc<RwLock<VecDeque<u64>>>,
}
unsafe impl Sync for Handshake {}
unsafe impl Send for Handshake {}
impl Handshake {
/// Creates a new handshake handler
pub fn new() -> Handshake {
Handshake { nonces: Arc::new(RwLock::new(VecDeque::with_capacity(NONCES_CAP))) }
}
/// Handles connecting to a new remote peer, starting the version handshake.
pub fn connect(&self,
capab: Capabilities,
total_difficulty: Difficulty,
self_addr: SocketAddr,
conn: TcpStream)
-> Box<Future<Item = (TcpStream, ProtocolV1, PeerInfo), Error = Error>> {
// prepare the first part of the hanshake
let nonce = self.next_nonce();
let hand = Hand {
version: PROTOCOL_VERSION,
capabilities: capab,
nonce: nonce,
total_difficulty: total_difficulty,
sender_addr: SockAddr(self_addr),
receiver_addr: SockAddr(conn.peer_addr().unwrap()),
user_agent: USER_AGENT.to_string(),
};
// write and read the handshake response
Box::new(write_msg(conn, hand, Type::Hand)
.and_then(|conn| read_msg::<Shake>(conn))
.and_then(|(conn, shake)| {
if shake.version!= 1 {
Err(Error::Serialization(ser::Error::UnexpectedData {
expected: vec![PROTOCOL_VERSION as u8],
received: vec![shake.version as u8],
}))
} else {
let peer_info = PeerInfo {
capabilities: shake.capabilities,
user_agent: shake.user_agent,
addr: conn.peer_addr().unwrap(),
version: shake.version,
total_difficulty: shake.total_difficulty,
};
info!("Connected to peer {:?}", peer_info);
// when more than one protocol version is supported, choosing should go here
Ok((conn, ProtocolV1::new(), peer_info))
}
}))
}
/// Handles receiving a connection from a new remote peer that started the
/// version handshake.
pub fn handshake(&self,
capab: Capabilities,
total_difficulty: Difficulty,
conn: TcpStream)
-> Box<Future<Item = (TcpStream, ProtocolV1, PeerInfo), Error = Error>> {
let nonces = self.nonces.clone();
Box::new(read_msg::<Hand>(conn)
.and_then(move |(conn, hand)| {
if hand.version!= 1 {
return Err(Error::Serialization(ser::Error::UnexpectedData {
expected: vec![PROTOCOL_VERSION as u8],
received: vec![hand.version as u8],
}));
}
{
// check the nonce to see if we could be trying to connect to ourselves
let nonces = nonces.read().unwrap();
if nonces.contains(&hand.nonce) {
return Err(Error::Serialization(ser::Error::UnexpectedData {
expected: vec![],
received: vec![],
}));
}
}
// all good, keep peer info
let peer_info = PeerInfo {
capabilities: hand.capabilities,
user_agent: hand.user_agent,
addr: hand.sender_addr.0,
version: hand.version,
total_difficulty: hand.total_difficulty,
};
// send our reply with our info
let shake = Shake {
version: PROTOCOL_VERSION,
capabilities: capab,
total_difficulty: total_difficulty,
user_agent: USER_AGENT.to_string(),
};
Ok((conn, shake, peer_info))
})
.and_then(|(conn, shake, peer_info)| {
debug!("Success handshake with {}.", peer_info.addr);
write_msg(conn, shake, Type::Shake)
// when more than one protocol version is supported, choosing should go here
.map(|conn| (conn, ProtocolV1::new(), peer_info))
}))
}
/// Generate a new random nonce and store it in our ring buffer
fn next_nonce(&self) -> u64 {
let mut rng = OsRng::new().unwrap();
let nonce = rng.next_u64();
let mut nonces = self.nonces.write().unwrap();
nonces.push_back(nonce);
if nonces.len() >= NONCES_CAP |
nonce
}
}
| {
nonces.pop_front();
} | conditional_block |
destructured-fn-argument.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// compile-flags:-Z extra-debug-info
// debugger:rbreak zzz
// debugger:run
// debugger:finish
// debugger:print a
// check:$1 = 1
// debugger:print b
// check:$2 = false
// debugger:continue
// debugger:finish
// debugger:print a
// check:$3 = 2
// debugger:print b
// check:$4 = 3
// debugger:print c
// check:$5 = 4
// debugger:continue
// debugger:finish
// debugger:print a
// check:$6 = 5
// debugger:print b
// check:$7 = {6, 7}
// debugger:continue
// debugger:finish
// debugger:print h
// check:$8 = 8
// debugger:print i
// check:$9 = {a = 9, b = 10}
// debugger:print j
// check:$10 = 11
// debugger:continue
// debugger:finish
// debugger:print k
// check:$11 = 12
// debugger:print l
// check:$12 = 13
// debugger:continue
// debugger:finish
// debugger:print m
// check:$13 = 14
// debugger:print n
// check:$14 = 16
// debugger:continue
// debugger:finish
// debugger:print o
// check:$15 = 18
// debugger:continue
// debugger:finish
// debugger:print p
// check:$16 = 19
// debugger:print q
// check:$17 = 20
// debugger:print r
// check:$18 = {a = 21, b = 22}
// debugger:continue
// debugger:finish
// debugger:print s
// check:$19 = 24
// debugger:print t
// check:$20 = 23
// debugger:continue
// debugger:finish
// debugger:print u
// check:$21 = 25
// debugger:print v
// check:$22 = 26
// debugger:print w
// check:$23 = 27
// debugger:print x
// check:$24 = 28
// debugger:print y
// check:$25 = 29
// debugger:print z
// check:$26 = 30
// debugger:print ae
// check:$27 = 31
// debugger:print oe
// check:$28 = 32
// debugger:print ue
// check:$29 = 33
// debugger:continue
// debugger:finish
// debugger:print aa
// check:$30 = {34, 35}
// debugger:continue
// debugger:finish
// debugger:print bb
// check:$31 = {36, 37}
// debugger:continue
// debugger:finish
// debugger:print cc
// check:$32 = 38
// debugger:continue
// debugger:finish
// debugger:print dd
// check:$33 = {40, 41, 42}
// debugger:continue
// debugger:finish
// debugger:print *ee
// check:$34 = {43, 44, 45}
// debugger:continue
// debugger:finish
// debugger:print *ff
// check:$35 = 46
// debugger:print gg
// check:$36 = {47, 48}
// debugger:continue
// debugger:finish
// debugger:print *hh
// check:$37 = 50
// debugger:continue
// debugger:finish
// debugger:print ii
// check:$38 = 51
// debugger:continue
// debugger:finish
// debugger:print *jj
// check:$39 = 52
// debugger:continue
// debugger:finish
// debugger:print kk
// check:$40 = 53
// debugger:print ll
// check:$41 = 54
// debugger:continue
// debugger:finish
// debugger:print mm
// check:$42 = 55
// debugger:print *nn
// check:$43 = 56
// debugger:continue
// debugger:finish
// debugger:print oo
// check:$44 = 57
// debugger:print pp
// check:$45 = 58
// debugger:print qq
// check:$46 = 59
// debugger:continue
// debugger:finish
// debugger:print rr
// check:$47 = 60
// debugger:print ss
// check:$48 = 61
// debugger:print tt
// check:$49 = 62
// debugger:continue
#[allow(unused_variable)];
struct Struct {
a: i64,
b: i32
}
enum Univariant {
Unit(i32)
}
struct TupleStruct (float, int);
fn simple_tuple((a, b): (int, bool)) {
zzz();
}
fn nested_tuple((a, (b, c)): (int, (u16, u16))) {
zzz();
}
fn destructure_only_first_level((a, b): (int, (u32, u32))) {
zzz();
}
fn struct_as_tuple_element((h, i, j): (i16, Struct, i16)) {
zzz();
}
fn struct_pattern(Struct { a: k, b: l }: Struct) {
zzz();
}
fn ignored_tuple_element((m, _, n): (int, u16, i32)) {
zzz();
}
fn ignored_struct_field(Struct { b: o, _ }: Struct) {
zzz();
}
fn one_struct_destructured_one_not((Struct { a: p, b: q }, r): (Struct, Struct)) {
zzz();
}
fn different_order_of_struct_fields(Struct { b: s, a: t }: Struct ) {
zzz();
}
fn complex_nesting(((u, v ), ((w, (x, Struct { a: y, b: z})), Struct { a: ae, b: oe }), ue ):
((i16, i32), ((i64, (i32, Struct, )), Struct ), u16)) {
zzz();
}
fn managed_box(@aa: @(int, int)) {
zzz();
}
fn borrowed_pointer(&bb: &(int, int)) {
zzz();
}
fn contained_borrowed_pointer((&cc, _): (&int, int)) {
zzz();
}
fn unique_pointer(~dd: ~(int, int, int)) {
zzz();
}
fn ref_binding(ref ee: (int, int, int)) {
zzz();
}
fn ref_binding_in_tuple((ref ff, gg): (int, (int, int))) {
zzz();
}
fn ref_binding_in_struct(Struct { b: ref hh, _ }: Struct) {
zzz();
}
fn univariant_enum(Unit(ii): Univariant) {
zzz();
}
fn univariant_enum_with_ref_binding(Unit(ref jj): Univariant) {
zzz();
}
fn tuple_struct(TupleStruct(kk, ll): TupleStruct) {
zzz();
}
fn tuple_struct_with_ref_binding(TupleStruct(mm, ref nn): TupleStruct) {
zzz();
}
fn multiple_arguments((oo, pp): (int, int), qq : int) {
zzz();
}
fn main() {
simple_tuple((1, false));
nested_tuple((2, (3, 4)));
destructure_only_first_level((5, (6, 7)));
struct_as_tuple_element((8, Struct { a: 9, b: 10 }, 11));
struct_pattern(Struct { a: 12, b: 13 });
ignored_tuple_element((14, 15, 16));
ignored_struct_field(Struct { a: 17, b: 18 });
one_struct_destructured_one_not((Struct { a: 19, b: 20 }, Struct { a: 21, b: 22 }));
different_order_of_struct_fields(Struct { a: 23, b: 24 });
complex_nesting(((25, 26), ((27, (28, Struct { a: 29, b: 30})), Struct { a: 31, b: 32 }), 33));
managed_box(@(34, 35));
borrowed_pointer(&(36, 37));
contained_borrowed_pointer((&38, 39));
unique_pointer(~(40, 41, 42));
ref_binding((43, 44, 45));
ref_binding_in_tuple((46, (47, 48)));
ref_binding_in_struct(Struct { a: 49, b: 50 });
univariant_enum(Unit(51));
univariant_enum_with_ref_binding(Unit(52));
tuple_struct(TupleStruct(53.0, 54));
tuple_struct_with_ref_binding(TupleStruct(55.0, 56));
multiple_arguments((57, 58), 59);
fn | (rr: int, (ss, tt): (int, int)) {
zzz();
}
nested_function(60, (61, 62));
}
fn zzz() {()}
| nested_function | identifier_name |
destructured-fn-argument.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// compile-flags:-Z extra-debug-info
// debugger:rbreak zzz
// debugger:run
// debugger:finish
// debugger:print a
// check:$1 = 1
// debugger:print b
// check:$2 = false
// debugger:continue
// debugger:finish
// debugger:print a
// check:$3 = 2
// debugger:print b
// check:$4 = 3
// debugger:print c
// check:$5 = 4
// debugger:continue
// debugger:finish
// debugger:print a
// check:$6 = 5
// debugger:print b
// check:$7 = {6, 7}
// debugger:continue
// debugger:finish
// debugger:print h
// check:$8 = 8
// debugger:print i
// check:$9 = {a = 9, b = 10}
// debugger:print j
// check:$10 = 11
// debugger:continue
// debugger:finish
// debugger:print k
// check:$11 = 12
// debugger:print l
// check:$12 = 13
// debugger:continue
// debugger:finish
// debugger:print m
// check:$13 = 14
// debugger:print n
// check:$14 = 16
// debugger:continue
// debugger:finish
// debugger:print o
// check:$15 = 18
// debugger:continue
// debugger:finish
// debugger:print p
// check:$16 = 19
// debugger:print q
// check:$17 = 20
// debugger:print r
// check:$18 = {a = 21, b = 22}
// debugger:continue
// debugger:finish
// debugger:print s
// check:$19 = 24
// debugger:print t
// check:$20 = 23
// debugger:continue
// debugger:finish
// debugger:print u
// check:$21 = 25
// debugger:print v
// check:$22 = 26
// debugger:print w
// check:$23 = 27
// debugger:print x
// check:$24 = 28
// debugger:print y
// check:$25 = 29
// debugger:print z
// check:$26 = 30
// debugger:print ae
// check:$27 = 31
// debugger:print oe
// check:$28 = 32
// debugger:print ue
// check:$29 = 33
// debugger:continue
// debugger:finish
// debugger:print aa
// check:$30 = {34, 35}
// debugger:continue
// debugger:finish
// debugger:print bb
// check:$31 = {36, 37}
// debugger:continue
// debugger:finish
// debugger:print cc
// check:$32 = 38
// debugger:continue
// debugger:finish
// debugger:print dd
// check:$33 = {40, 41, 42}
// debugger:continue
// debugger:finish
// debugger:print *ee
// check:$34 = {43, 44, 45}
// debugger:continue
// debugger:finish
// debugger:print *ff
// check:$35 = 46
// debugger:print gg
// check:$36 = {47, 48}
// debugger:continue
// debugger:finish
// debugger:print *hh
// check:$37 = 50
// debugger:continue
// debugger:finish
// debugger:print ii
// check:$38 = 51
// debugger:continue
// debugger:finish
// debugger:print *jj
// check:$39 = 52
// debugger:continue
// debugger:finish
// debugger:print kk
// check:$40 = 53
// debugger:print ll
// check:$41 = 54
// debugger:continue
// debugger:finish
// debugger:print mm
// check:$42 = 55
// debugger:print *nn
// check:$43 = 56
// debugger:continue
// debugger:finish
// debugger:print oo
// check:$44 = 57
// debugger:print pp
// check:$45 = 58
// debugger:print qq
// check:$46 = 59
// debugger:continue
// debugger:finish
// debugger:print rr
// check:$47 = 60
// debugger:print ss
// check:$48 = 61
// debugger:print tt
// check:$49 = 62
// debugger:continue
#[allow(unused_variable)];
struct Struct {
a: i64,
b: i32
}
enum Univariant {
Unit(i32)
}
struct TupleStruct (float, int);
fn simple_tuple((a, b): (int, bool)) {
zzz();
}
fn nested_tuple((a, (b, c)): (int, (u16, u16))) {
zzz();
}
fn destructure_only_first_level((a, b): (int, (u32, u32))) {
zzz();
}
fn struct_as_tuple_element((h, i, j): (i16, Struct, i16)) {
zzz();
}
fn struct_pattern(Struct { a: k, b: l }: Struct) {
zzz();
}
fn ignored_tuple_element((m, _, n): (int, u16, i32)) {
zzz();
}
fn ignored_struct_field(Struct { b: o, _ }: Struct) {
zzz();
}
fn one_struct_destructured_one_not((Struct { a: p, b: q }, r): (Struct, Struct)) |
fn different_order_of_struct_fields(Struct { b: s, a: t }: Struct ) {
zzz();
}
fn complex_nesting(((u, v ), ((w, (x, Struct { a: y, b: z})), Struct { a: ae, b: oe }), ue ):
((i16, i32), ((i64, (i32, Struct, )), Struct ), u16)) {
zzz();
}
fn managed_box(@aa: @(int, int)) {
zzz();
}
fn borrowed_pointer(&bb: &(int, int)) {
zzz();
}
fn contained_borrowed_pointer((&cc, _): (&int, int)) {
zzz();
}
fn unique_pointer(~dd: ~(int, int, int)) {
zzz();
}
fn ref_binding(ref ee: (int, int, int)) {
zzz();
}
fn ref_binding_in_tuple((ref ff, gg): (int, (int, int))) {
zzz();
}
fn ref_binding_in_struct(Struct { b: ref hh, _ }: Struct) {
zzz();
}
fn univariant_enum(Unit(ii): Univariant) {
zzz();
}
fn univariant_enum_with_ref_binding(Unit(ref jj): Univariant) {
zzz();
}
fn tuple_struct(TupleStruct(kk, ll): TupleStruct) {
zzz();
}
fn tuple_struct_with_ref_binding(TupleStruct(mm, ref nn): TupleStruct) {
zzz();
}
fn multiple_arguments((oo, pp): (int, int), qq : int) {
zzz();
}
fn main() {
simple_tuple((1, false));
nested_tuple((2, (3, 4)));
destructure_only_first_level((5, (6, 7)));
struct_as_tuple_element((8, Struct { a: 9, b: 10 }, 11));
struct_pattern(Struct { a: 12, b: 13 });
ignored_tuple_element((14, 15, 16));
ignored_struct_field(Struct { a: 17, b: 18 });
one_struct_destructured_one_not((Struct { a: 19, b: 20 }, Struct { a: 21, b: 22 }));
different_order_of_struct_fields(Struct { a: 23, b: 24 });
complex_nesting(((25, 26), ((27, (28, Struct { a: 29, b: 30})), Struct { a: 31, b: 32 }), 33));
managed_box(@(34, 35));
borrowed_pointer(&(36, 37));
contained_borrowed_pointer((&38, 39));
unique_pointer(~(40, 41, 42));
ref_binding((43, 44, 45));
ref_binding_in_tuple((46, (47, 48)));
ref_binding_in_struct(Struct { a: 49, b: 50 });
univariant_enum(Unit(51));
univariant_enum_with_ref_binding(Unit(52));
tuple_struct(TupleStruct(53.0, 54));
tuple_struct_with_ref_binding(TupleStruct(55.0, 56));
multiple_arguments((57, 58), 59);
fn nested_function(rr: int, (ss, tt): (int, int)) {
zzz();
}
nested_function(60, (61, 62));
}
fn zzz() {()}
| {
zzz();
} | identifier_body |
destructured-fn-argument.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// compile-flags:-Z extra-debug-info
// debugger:rbreak zzz
// debugger:run
// debugger:finish
// debugger:print a
// check:$1 = 1
// debugger:print b
// check:$2 = false
// debugger:continue
// debugger:finish
// debugger:print a
// check:$3 = 2
// debugger:print b
// check:$4 = 3
// debugger:print c
// check:$5 = 4
// debugger:continue
// debugger:finish
// debugger:print a
// check:$6 = 5
// debugger:print b
// check:$7 = {6, 7}
// debugger:continue
// debugger:finish
// debugger:print h
// check:$8 = 8
// debugger:print i
// check:$9 = {a = 9, b = 10}
// debugger:print j
// check:$10 = 11
// debugger:continue
// debugger:finish
// debugger:print k
// check:$11 = 12
// debugger:print l
// check:$12 = 13
// debugger:continue
// debugger:finish
// debugger:print m
// check:$13 = 14
// debugger:print n
// check:$14 = 16
// debugger:continue
// debugger:finish
// debugger:print o
// check:$15 = 18
// debugger:continue
// debugger:finish
// debugger:print p
// check:$16 = 19
// debugger:print q
// check:$17 = 20
// debugger:print r
// check:$18 = {a = 21, b = 22}
// debugger:continue
// debugger:finish
// debugger:print s
// check:$19 = 24
// debugger:print t
// check:$20 = 23
// debugger:continue
// debugger:finish
// debugger:print u
// check:$21 = 25
// debugger:print v
// check:$22 = 26
// debugger:print w
// check:$23 = 27
// debugger:print x
// check:$24 = 28
// debugger:print y
// check:$25 = 29
// debugger:print z
// check:$26 = 30
// debugger:print ae
// check:$27 = 31
// debugger:print oe
// check:$28 = 32
// debugger:print ue
// check:$29 = 33
// debugger:continue
// debugger:finish
// debugger:print aa
// check:$30 = {34, 35}
// debugger:continue
// debugger:finish
// debugger:print bb
// check:$31 = {36, 37}
// debugger:continue
// debugger:finish
// debugger:print cc
// check:$32 = 38
// debugger:continue
// debugger:finish
// debugger:print dd
// check:$33 = {40, 41, 42}
// debugger:continue
// debugger:finish
// debugger:print *ee
// check:$34 = {43, 44, 45}
// debugger:continue
// debugger:finish
// debugger:print *ff
// check:$35 = 46
// debugger:print gg
// check:$36 = {47, 48}
// debugger:continue
// debugger:finish
// debugger:print *hh
// check:$37 = 50
// debugger:continue
// debugger:finish
// debugger:print ii
// check:$38 = 51
// debugger:continue
// debugger:finish |
// debugger:finish
// debugger:print kk
// check:$40 = 53
// debugger:print ll
// check:$41 = 54
// debugger:continue
// debugger:finish
// debugger:print mm
// check:$42 = 55
// debugger:print *nn
// check:$43 = 56
// debugger:continue
// debugger:finish
// debugger:print oo
// check:$44 = 57
// debugger:print pp
// check:$45 = 58
// debugger:print qq
// check:$46 = 59
// debugger:continue
// debugger:finish
// debugger:print rr
// check:$47 = 60
// debugger:print ss
// check:$48 = 61
// debugger:print tt
// check:$49 = 62
// debugger:continue
#[allow(unused_variable)];
struct Struct {
a: i64,
b: i32
}
enum Univariant {
Unit(i32)
}
struct TupleStruct (float, int);
fn simple_tuple((a, b): (int, bool)) {
zzz();
}
fn nested_tuple((a, (b, c)): (int, (u16, u16))) {
zzz();
}
fn destructure_only_first_level((a, b): (int, (u32, u32))) {
zzz();
}
fn struct_as_tuple_element((h, i, j): (i16, Struct, i16)) {
zzz();
}
fn struct_pattern(Struct { a: k, b: l }: Struct) {
zzz();
}
fn ignored_tuple_element((m, _, n): (int, u16, i32)) {
zzz();
}
fn ignored_struct_field(Struct { b: o, _ }: Struct) {
zzz();
}
fn one_struct_destructured_one_not((Struct { a: p, b: q }, r): (Struct, Struct)) {
zzz();
}
fn different_order_of_struct_fields(Struct { b: s, a: t }: Struct ) {
zzz();
}
fn complex_nesting(((u, v ), ((w, (x, Struct { a: y, b: z})), Struct { a: ae, b: oe }), ue ):
((i16, i32), ((i64, (i32, Struct, )), Struct ), u16)) {
zzz();
}
fn managed_box(@aa: @(int, int)) {
zzz();
}
fn borrowed_pointer(&bb: &(int, int)) {
zzz();
}
fn contained_borrowed_pointer((&cc, _): (&int, int)) {
zzz();
}
fn unique_pointer(~dd: ~(int, int, int)) {
zzz();
}
fn ref_binding(ref ee: (int, int, int)) {
zzz();
}
fn ref_binding_in_tuple((ref ff, gg): (int, (int, int))) {
zzz();
}
fn ref_binding_in_struct(Struct { b: ref hh, _ }: Struct) {
zzz();
}
fn univariant_enum(Unit(ii): Univariant) {
zzz();
}
fn univariant_enum_with_ref_binding(Unit(ref jj): Univariant) {
zzz();
}
fn tuple_struct(TupleStruct(kk, ll): TupleStruct) {
zzz();
}
fn tuple_struct_with_ref_binding(TupleStruct(mm, ref nn): TupleStruct) {
zzz();
}
fn multiple_arguments((oo, pp): (int, int), qq : int) {
zzz();
}
fn main() {
simple_tuple((1, false));
nested_tuple((2, (3, 4)));
destructure_only_first_level((5, (6, 7)));
struct_as_tuple_element((8, Struct { a: 9, b: 10 }, 11));
struct_pattern(Struct { a: 12, b: 13 });
ignored_tuple_element((14, 15, 16));
ignored_struct_field(Struct { a: 17, b: 18 });
one_struct_destructured_one_not((Struct { a: 19, b: 20 }, Struct { a: 21, b: 22 }));
different_order_of_struct_fields(Struct { a: 23, b: 24 });
complex_nesting(((25, 26), ((27, (28, Struct { a: 29, b: 30})), Struct { a: 31, b: 32 }), 33));
managed_box(@(34, 35));
borrowed_pointer(&(36, 37));
contained_borrowed_pointer((&38, 39));
unique_pointer(~(40, 41, 42));
ref_binding((43, 44, 45));
ref_binding_in_tuple((46, (47, 48)));
ref_binding_in_struct(Struct { a: 49, b: 50 });
univariant_enum(Unit(51));
univariant_enum_with_ref_binding(Unit(52));
tuple_struct(TupleStruct(53.0, 54));
tuple_struct_with_ref_binding(TupleStruct(55.0, 56));
multiple_arguments((57, 58), 59);
fn nested_function(rr: int, (ss, tt): (int, int)) {
zzz();
}
nested_function(60, (61, 62));
}
fn zzz() {()} | // debugger:print *jj
// check:$39 = 52
// debugger:continue | random_line_split |
titles.rs | #![crate_name = "foo"]
// @matches 'foo/index.html' '//h1' 'Crate foo'
// @matches 'foo/foo_mod/index.html' '//h1' 'Module foo::foo_mod'
pub mod foo_mod {
pub struct __Thing {}
}
extern "C" {
// @matches 'foo/fn.foo_ffn.html' '//h1' 'Function foo::foo_ffn'
pub fn foo_ffn();
}
// @matches 'foo/fn.foo_fn.html' '//h1' 'Function foo::foo_fn'
pub fn foo_fn() {}
// @matches 'foo/trait.FooTrait.html' '//h1' 'Trait foo::FooTrait'
pub trait FooTrait {}
// @matches 'foo/struct.FooStruct.html' '//h1' 'Struct foo::FooStruct'
pub struct FooStruct;
// @matches 'foo/enum.FooEnum.html' '//h1' 'Enum foo::FooEnum'
pub enum FooEnum {}
// @matches 'foo/type.FooType.html' '//h1' 'Type Definition foo::FooType'
pub type FooType = FooStruct;
// @matches 'foo/macro.foo_macro.html' '//h1' 'Macro foo::foo_macro'
#[macro_export]
macro_rules! foo_macro {
() => {};
} | // @matches 'foo/primitive.bool.html' '//h1' 'Primitive Type bool'
#[doc(primitive = "bool")]
mod bool {}
// @matches 'foo/static.FOO_STATIC.html' '//h1' 'Static foo::FOO_STATIC'
pub static FOO_STATIC: FooStruct = FooStruct;
extern "C" {
// @matches 'foo/static.FOO_FSTATIC.html' '//h1' 'Static foo::FOO_FSTATIC'
pub static FOO_FSTATIC: FooStruct;
}
// @matches 'foo/constant.FOO_CONSTANT.html' '//h1' 'Constant foo::FOO_CONSTANT'
pub const FOO_CONSTANT: FooStruct = FooStruct; | random_line_split | |
titles.rs | #![crate_name = "foo"]
// @matches 'foo/index.html' '//h1' 'Crate foo'
// @matches 'foo/foo_mod/index.html' '//h1' 'Module foo::foo_mod'
pub mod foo_mod {
pub struct | {}
}
extern "C" {
// @matches 'foo/fn.foo_ffn.html' '//h1' 'Function foo::foo_ffn'
pub fn foo_ffn();
}
// @matches 'foo/fn.foo_fn.html' '//h1' 'Function foo::foo_fn'
pub fn foo_fn() {}
// @matches 'foo/trait.FooTrait.html' '//h1' 'Trait foo::FooTrait'
pub trait FooTrait {}
// @matches 'foo/struct.FooStruct.html' '//h1' 'Struct foo::FooStruct'
pub struct FooStruct;
// @matches 'foo/enum.FooEnum.html' '//h1' 'Enum foo::FooEnum'
pub enum FooEnum {}
// @matches 'foo/type.FooType.html' '//h1' 'Type Definition foo::FooType'
pub type FooType = FooStruct;
// @matches 'foo/macro.foo_macro.html' '//h1' 'Macro foo::foo_macro'
#[macro_export]
macro_rules! foo_macro {
() => {};
}
// @matches 'foo/primitive.bool.html' '//h1' 'Primitive Type bool'
#[doc(primitive = "bool")]
mod bool {}
// @matches 'foo/static.FOO_STATIC.html' '//h1' 'Static foo::FOO_STATIC'
pub static FOO_STATIC: FooStruct = FooStruct;
extern "C" {
// @matches 'foo/static.FOO_FSTATIC.html' '//h1' 'Static foo::FOO_FSTATIC'
pub static FOO_FSTATIC: FooStruct;
}
// @matches 'foo/constant.FOO_CONSTANT.html' '//h1' 'Constant foo::FOO_CONSTANT'
pub const FOO_CONSTANT: FooStruct = FooStruct;
| __Thing | identifier_name |
v1.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! This is an internal module used by the ifmt! runtime. These structures are
//! emitted to static arrays to precompile format strings ahead of time.
//!
//! These definitions are similar to their `ct` equivalents, but differ in that
//! these can be statically allocated and are slightly optimized for the runtime
#![cfg_attr(stage0, stable(feature = "rust1", since = "1.0.0"))]
#![cfg_attr(not(stage0), unstable(feature = "core", reason = "internal to format_args!"))]
#[derive(Copy, Clone)]
#[cfg_attr(stage0, stable(feature = "rust1", since = "1.0.0"))]
pub struct Argument {
#[cfg_attr(stage0, stable(feature = "rust1", since = "1.0.0"))]
pub position: Position,
#[cfg_attr(stage0, stable(feature = "rust1", since = "1.0.0"))]
pub format: FormatSpec,
}
#[derive(Copy, Clone)]
#[cfg_attr(stage0, stable(feature = "rust1", since = "1.0.0"))]
pub struct | {
#[cfg_attr(stage0, stable(feature = "rust1", since = "1.0.0"))]
pub fill: char,
#[cfg_attr(stage0, stable(feature = "rust1", since = "1.0.0"))]
pub align: Alignment,
#[cfg_attr(stage0, stable(feature = "rust1", since = "1.0.0"))]
pub flags: u32,
#[cfg_attr(stage0, stable(feature = "rust1", since = "1.0.0"))]
pub precision: Count,
#[cfg_attr(stage0, stable(feature = "rust1", since = "1.0.0"))]
pub width: Count,
}
/// Possible alignments that can be requested as part of a formatting directive.
#[derive(Copy, Clone, PartialEq)]
#[cfg_attr(stage0, stable(feature = "rust1", since = "1.0.0"))]
pub enum Alignment {
/// Indication that contents should be left-aligned.
#[cfg_attr(stage0, stable(feature = "rust1", since = "1.0.0"))]
Left,
/// Indication that contents should be right-aligned.
#[cfg_attr(stage0, stable(feature = "rust1", since = "1.0.0"))]
Right,
/// Indication that contents should be center-aligned.
#[cfg_attr(stage0, stable(feature = "rust1", since = "1.0.0"))]
Center,
/// No alignment was requested.
#[cfg_attr(stage0, stable(feature = "rust1", since = "1.0.0"))]
Unknown,
}
#[derive(Copy, Clone)]
#[cfg_attr(stage0, stable(feature = "rust1", since = "1.0.0"))]
pub enum Count {
#[cfg_attr(stage0, stable(feature = "rust1", since = "1.0.0"))]
Is(usize),
#[cfg_attr(stage0, stable(feature = "rust1", since = "1.0.0"))]
Param(usize),
#[cfg_attr(stage0, stable(feature = "rust1", since = "1.0.0"))]
NextParam,
#[cfg_attr(stage0, stable(feature = "rust1", since = "1.0.0"))]
Implied,
}
#[derive(Copy, Clone)]
#[cfg_attr(stage0, stable(feature = "rust1", since = "1.0.0"))]
pub enum Position {
#[cfg_attr(stage0, stable(feature = "rust1", since = "1.0.0"))]
Next,
#[cfg_attr(stage0, stable(feature = "rust1", since = "1.0.0"))]
At(usize)
}
| FormatSpec | identifier_name |
v1.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! This is an internal module used by the ifmt! runtime. These structures are
//! emitted to static arrays to precompile format strings ahead of time.
//!
//! These definitions are similar to their `ct` equivalents, but differ in that
//! these can be statically allocated and are slightly optimized for the runtime
#![cfg_attr(stage0, stable(feature = "rust1", since = "1.0.0"))]
#![cfg_attr(not(stage0), unstable(feature = "core", reason = "internal to format_args!"))]
#[derive(Copy, Clone)]
#[cfg_attr(stage0, stable(feature = "rust1", since = "1.0.0"))]
pub struct Argument {
#[cfg_attr(stage0, stable(feature = "rust1", since = "1.0.0"))]
pub position: Position,
#[cfg_attr(stage0, stable(feature = "rust1", since = "1.0.0"))]
pub format: FormatSpec,
}
#[derive(Copy, Clone)]
#[cfg_attr(stage0, stable(feature = "rust1", since = "1.0.0"))]
pub struct FormatSpec {
#[cfg_attr(stage0, stable(feature = "rust1", since = "1.0.0"))]
pub fill: char,
#[cfg_attr(stage0, stable(feature = "rust1", since = "1.0.0"))]
pub align: Alignment,
#[cfg_attr(stage0, stable(feature = "rust1", since = "1.0.0"))]
pub flags: u32,
#[cfg_attr(stage0, stable(feature = "rust1", since = "1.0.0"))]
pub precision: Count,
#[cfg_attr(stage0, stable(feature = "rust1", since = "1.0.0"))]
pub width: Count,
}
/// Possible alignments that can be requested as part of a formatting directive.
#[derive(Copy, Clone, PartialEq)]
#[cfg_attr(stage0, stable(feature = "rust1", since = "1.0.0"))]
pub enum Alignment {
/// Indication that contents should be left-aligned.
#[cfg_attr(stage0, stable(feature = "rust1", since = "1.0.0"))] | /// Indication that contents should be right-aligned.
#[cfg_attr(stage0, stable(feature = "rust1", since = "1.0.0"))]
Right,
/// Indication that contents should be center-aligned.
#[cfg_attr(stage0, stable(feature = "rust1", since = "1.0.0"))]
Center,
/// No alignment was requested.
#[cfg_attr(stage0, stable(feature = "rust1", since = "1.0.0"))]
Unknown,
}
#[derive(Copy, Clone)]
#[cfg_attr(stage0, stable(feature = "rust1", since = "1.0.0"))]
pub enum Count {
#[cfg_attr(stage0, stable(feature = "rust1", since = "1.0.0"))]
Is(usize),
#[cfg_attr(stage0, stable(feature = "rust1", since = "1.0.0"))]
Param(usize),
#[cfg_attr(stage0, stable(feature = "rust1", since = "1.0.0"))]
NextParam,
#[cfg_attr(stage0, stable(feature = "rust1", since = "1.0.0"))]
Implied,
}
#[derive(Copy, Clone)]
#[cfg_attr(stage0, stable(feature = "rust1", since = "1.0.0"))]
pub enum Position {
#[cfg_attr(stage0, stable(feature = "rust1", since = "1.0.0"))]
Next,
#[cfg_attr(stage0, stable(feature = "rust1", since = "1.0.0"))]
At(usize)
} | Left, | random_line_split |
htmlformelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::HTMLFormElementBinding;
use dom::bindings::codegen::InheritTypes::HTMLFormElementDerived;
use dom::bindings::js::{JSRef, Temporary};
use dom::bindings::utils::{Reflectable, Reflector};
use dom::document::Document;
use dom::element::HTMLFormElementTypeId;
use dom::eventtarget::{EventTarget, NodeTargetTypeId};
use dom::htmlelement::HTMLElement;
use dom::node::{Node, ElementNodeTypeId};
use servo_util::str::DOMString;
#[deriving(Encodable)]
#[must_root]
pub struct | {
pub htmlelement: HTMLElement
}
impl HTMLFormElementDerived for EventTarget {
fn is_htmlformelement(&self) -> bool {
self.type_id == NodeTargetTypeId(ElementNodeTypeId(HTMLFormElementTypeId))
}
}
impl HTMLFormElement {
pub fn new_inherited(localName: DOMString, document: JSRef<Document>) -> HTMLFormElement {
HTMLFormElement {
htmlelement: HTMLElement::new_inherited(HTMLFormElementTypeId, localName, document)
}
}
#[allow(unrooted_must_root)]
pub fn new(localName: DOMString, document: JSRef<Document>) -> Temporary<HTMLFormElement> {
let element = HTMLFormElement::new_inherited(localName, document);
Node::reflect_node(box element, document, HTMLFormElementBinding::Wrap)
}
}
impl Reflectable for HTMLFormElement {
fn reflector<'a>(&'a self) -> &'a Reflector {
self.htmlelement.reflector()
}
}
| HTMLFormElement | identifier_name |
htmlformelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::HTMLFormElementBinding;
use dom::bindings::codegen::InheritTypes::HTMLFormElementDerived;
use dom::bindings::js::{JSRef, Temporary};
use dom::bindings::utils::{Reflectable, Reflector};
use dom::document::Document;
use dom::element::HTMLFormElementTypeId;
use dom::eventtarget::{EventTarget, NodeTargetTypeId};
use dom::htmlelement::HTMLElement;
use dom::node::{Node, ElementNodeTypeId};
use servo_util::str::DOMString;
#[deriving(Encodable)]
#[must_root]
pub struct HTMLFormElement {
pub htmlelement: HTMLElement
}
impl HTMLFormElementDerived for EventTarget {
fn is_htmlformelement(&self) -> bool {
self.type_id == NodeTargetTypeId(ElementNodeTypeId(HTMLFormElementTypeId))
}
}
impl HTMLFormElement { |
#[allow(unrooted_must_root)]
pub fn new(localName: DOMString, document: JSRef<Document>) -> Temporary<HTMLFormElement> {
let element = HTMLFormElement::new_inherited(localName, document);
Node::reflect_node(box element, document, HTMLFormElementBinding::Wrap)
}
}
impl Reflectable for HTMLFormElement {
fn reflector<'a>(&'a self) -> &'a Reflector {
self.htmlelement.reflector()
}
} | pub fn new_inherited(localName: DOMString, document: JSRef<Document>) -> HTMLFormElement {
HTMLFormElement {
htmlelement: HTMLElement::new_inherited(HTMLFormElementTypeId, localName, document)
}
} | random_line_split |
htmlformelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::HTMLFormElementBinding;
use dom::bindings::codegen::InheritTypes::HTMLFormElementDerived;
use dom::bindings::js::{JSRef, Temporary};
use dom::bindings::utils::{Reflectable, Reflector};
use dom::document::Document;
use dom::element::HTMLFormElementTypeId;
use dom::eventtarget::{EventTarget, NodeTargetTypeId};
use dom::htmlelement::HTMLElement;
use dom::node::{Node, ElementNodeTypeId};
use servo_util::str::DOMString;
#[deriving(Encodable)]
#[must_root]
pub struct HTMLFormElement {
pub htmlelement: HTMLElement
}
impl HTMLFormElementDerived for EventTarget {
fn is_htmlformelement(&self) -> bool |
}
impl HTMLFormElement {
pub fn new_inherited(localName: DOMString, document: JSRef<Document>) -> HTMLFormElement {
HTMLFormElement {
htmlelement: HTMLElement::new_inherited(HTMLFormElementTypeId, localName, document)
}
}
#[allow(unrooted_must_root)]
pub fn new(localName: DOMString, document: JSRef<Document>) -> Temporary<HTMLFormElement> {
let element = HTMLFormElement::new_inherited(localName, document);
Node::reflect_node(box element, document, HTMLFormElementBinding::Wrap)
}
}
impl Reflectable for HTMLFormElement {
fn reflector<'a>(&'a self) -> &'a Reflector {
self.htmlelement.reflector()
}
}
| {
self.type_id == NodeTargetTypeId(ElementNodeTypeId(HTMLFormElementTypeId))
} | identifier_body |
load_info.rs | use crate::errors::*;
use crate::filesystem::readers::ExtraReader;
use crate::filesystem::FileSystem;
use crate::filesystem::Translator;
use crate::kernel::execve::binfmt::elf::{ElfHeader, ExecutableClass, ProgramHeader};
use crate::kernel::execve::binfmt::elf::{PF_R, PF_W, PF_X, PT_GNU_STACK, PT_INTERP, PT_LOAD};
use crate::register::Word;
use nix::sys::mman::MapFlags;
use nix::sys::mman::ProtFlags;
use nix::unistd::{sysconf, SysconfVar};
use std::fs::File;
use std::io::{Seek, SeekFrom};
use std::path::{Path, PathBuf};
#[derive(Debug, PartialEq)]
pub struct Mapping {
pub addr: Word,
pub length: Word,
pub clear_length: Word,
pub prot: ProtFlags,
pub flags: MapFlags,
pub fd: Option<Word>,
pub offset: Word,
}
// TODO: redesign this struct and remove unnecessary `Option`
#[derive(Debug, PartialEq)]
pub struct LoadInfo {
pub raw_path: Option<PathBuf>,
pub user_path: Option<PathBuf>,
pub host_path: Option<PathBuf>,
pub elf_header: ElfHeader,
pub mappings: Vec<Mapping>,
pub interp: Option<Box<LoadInfo>>,
pub needs_executable_stack: bool,
}
lazy_static! {
static ref PAGE_SIZE: Word = match sysconf(SysconfVar::PAGE_SIZE) {
Ok(Some(value)) => value as Word,
_ => 0x1000,
};
static ref PAGE_MASK: Word =!(*PAGE_SIZE - 1);
}
//TODO: move these in arch.rs and do cfg for each env
#[cfg(target_arch = "x86")]
const EXEC_PIC_ADDRESS: Word = 0x0f000000;
#[cfg(target_arch = "x86")]
const INTERP_PIC_ADDRESS: Word = 0xaf000000;
#[cfg(target_arch = "x86_64")]
const EXEC_PIC_ADDRESS: Word = 0x500000000000;
#[cfg(target_arch = "x86_64")]
const INTERP_PIC_ADDRESS: Word = 0x6f0000000000;
#[cfg(target_arch = "x86_64")]
const EXEC_PIC_ADDRESS_32: Word = 0x0f000000;
#[cfg(target_arch = "x86_64")]
const INTERP_PIC_ADDRESS_32: Word = 0xaf000000;
#[cfg(target_arch = "arm")]
const EXEC_PIC_ADDRESS: Word = 0x0f000000;
#[cfg(target_arch = "arm")]
const INTERP_PIC_ADDRESS: Word = 0x1f000000;
#[cfg(target_arch = "aarch64")]
const EXEC_PIC_ADDRESS: Word = 0x3000000000;
#[cfg(target_arch = "aarch64")]
const INTERP_PIC_ADDRESS: Word = 0x3f00000000;
impl LoadInfo {
fn new(elf_header: ElfHeader) -> Self {
Self {
raw_path: None,
user_path: None,
host_path: None,
elf_header: elf_header,
mappings: Vec::new(),
interp: None,
needs_executable_stack: false,
}
}
/// Extracts information about an executable:
/// - the ELF header info
/// - the program header segments, which contain:
/// - mappings
/// - interp???
pub fn from(fs: &FileSystem, host_path: &Path) -> Result<LoadInfo> {
let mut file = File::open(host_path)?;
let (elf_header, mut file) = ElfHeader::extract_from(&mut file)?;
// Sanity checks.
apply!(elf_header, |header| header.is_exec_or_dyn())?;
apply!(elf_header, |header| header.is_known_phentsize())?;
let executable_class = elf_header.get_class();
let program_headers_offset = get!(elf_header, e_phoff, u64)?;
let program_headers_count = get!(elf_header, e_phnum)?;
// We skip the initial part, directly to the program headers.
file.seek(SeekFrom::Start(program_headers_offset))?;
let mut load_info = LoadInfo::new(elf_header);
// We will read all the program headers, and extract info from them.
for _ in 0..program_headers_count {
let program_header = match executable_class {
ExecutableClass::Class32 => ProgramHeader::ProgramHeader32(file.read_struct()?),
ExecutableClass::Class64 => ProgramHeader::ProgramHeader64(file.read_struct()?),
};
let segment_type = get!(program_header, p_type)?;
match segment_type {
// Loadable segment. The bytes from the file are mapped to the beginning of the
// memory segment
PT_LOAD => load_info.add_mapping(&program_header)?,
// Specifies the location and size of a null-terminated path name to invoke as an
// interpreter.
PT_INTERP => load_info.add_interp(fs, &program_header, &mut file)?,
// Check if the stack of this executable file is executable (NX disabled)
PT_GNU_STACK => {
let flags = get!(program_header, p_flags)?;
let prot = process_prot_flags(flags);
load_info.needs_executable_stack = prot.contains(ProtFlags::PROT_EXEC);
}
_ => (),
};
}
Ok(load_info)
}
/// Processes a program header segment into a Mapping,
/// which is then added to the mappings list.
fn add_mapping(&mut self, program_header: &ProgramHeader) -> Result<()> {
let vaddr = get!(program_header, p_vaddr, Word)?;
let memsz = get!(program_header, p_memsz, Word)?;
let filesz = get!(program_header, p_filesz, Word)?;
let offset = get!(program_header, p_offset, Word)?;
let flags = get!(program_header, p_flags)?;
let start_address = vaddr & *PAGE_MASK;
let end_address = (vaddr + filesz + *PAGE_SIZE) & *PAGE_MASK;
let prot = process_prot_flags(flags);
let mut mapping = Mapping {
fd: None, // unknown yet
offset: offset & *PAGE_MASK,
addr: start_address,
// TODO: This can be optimized.
// The calculation of the `length` may be wrong. The field `length` should not be
// calculated using the paged-aligned `end_address`. It will cause more content in the
// target file to be mapped into the memory area. Due to `clear_length`, the
// over-mapped area is later cleared by `clear_length`. However, according to the man
// page of mmap(2), the remaining bytes of a file mapping will be zeroed automatically.
// So the best way is to correct the calculation of `length` and remove `clear_length`
// field.
length: end_address - start_address,
flags: MapFlags::MAP_PRIVATE | MapFlags::MAP_FIXED,
prot: prot,
clear_length: 0,
};
// According to the description in man page elf(5), `p_filesz` may not be larger
// than the `p_memsz`.
// "If the segment's memory size p_memsz is larger than the
// file size p_filesz, the "extra" bytes are defined to hold
// the value 0 and to follow the segment's initialized area."
// -- man 5 elf.
if memsz > filesz {
// How many extra bytes in the current page?
mapping.clear_length = end_address - vaddr - filesz;
self.mappings.push(mapping);
let start_address = end_address;
let end_address = (vaddr + memsz + *PAGE_SIZE) & *PAGE_MASK;
// Create new pages for the remaining extra bytes.
if end_address > start_address {
let new_mapping = Mapping {
fd: None,
offset: 0,
addr: start_address,
length: end_address - start_address,
clear_length: 0,
flags: MapFlags::MAP_PRIVATE | MapFlags::MAP_ANONYMOUS | MapFlags::MAP_FIXED,
prot: prot,
};
self.mappings.push(new_mapping);
}
} else {
self.mappings.push(mapping);
}
Ok(())
}
fn add_interp(
&mut self,
fs: &FileSystem,
program_header: &ProgramHeader,
file: &mut File,
) -> Result<()> {
// Only one PT_INTERP segment is allowed.
if self.interp.is_some() {
return Err(Error::errno_with_msg(
EINVAL,
"when translating execve, double interp",
));
}
let user_path_size = get!(program_header, p_filesz, usize)?;
let user_path_offset = get!(program_header, p_offset, u64)?;
// the -1 is to avoid the null char `\0`
let user_path = file.pread_path_at(user_path_size - 1, user_path_offset)?;
//TODO: implement load info for QEMU
// /* When a QEMU command was specified:
// *
// * - if it's a foreign binary we are reading the ELF
// * interpreter of QEMU instead.
// *
// * - if it's a host binary, we are reading its ELF
// * interpreter.
// *
// * In both case, it lies in "/host-rootfs" from a guest
// * point-of-view. */
// if (tracee->qemu!= NULL && user_path[0] == '/') {
// user_path = talloc_asprintf(tracee->ctx, "%s%s", HOST_ROOTFS,
// user_path); if (user_path == NULL)
// return -ENOMEM;
// }
let host_path = fs.translate_path(&user_path, true)?.1;
FileSystem::check_host_path_executable(&host_path)?;
let mut load_info = LoadInfo::from(fs, &host_path)?;
load_info.host_path = Some(host_path);
load_info.user_path = Some(user_path);
self.interp = Some(Box::new(load_info));
Ok(())
}
/// Add @load_base to each adresses of @load_info.
#[inline]
fn add_load_base(&mut self, load_base: Word) -> Result<()> {
for mapping in &mut self.mappings {
mapping.addr += load_base;
}
self.elf_header.apply_mut(
|mut header32| {
header32.e_entry += load_base as u32;
Ok(())
},
|mut header64| {
header64.e_entry += load_base as u64;
Ok(())
},
)
}
/// Compute the final load address for each position independent objects of
/// @tracee.
pub fn compute_load_addresses(&mut self, is_interp: bool) -> Result<()> {
let is_pos_indep = apply!(self.elf_header, |header| header.is_position_independent())?;
if is_pos_indep && self.mappings.get(0).unwrap().addr == 0 {
#[cfg(target_arch = "x86_64")]
let load_base_32 = match is_interp {
false => EXEC_PIC_ADDRESS_32, // exec
true => INTERP_PIC_ADDRESS_32, // interp
};
let load_base = match is_interp {
false => EXEC_PIC_ADDRESS, // exec
true => INTERP_PIC_ADDRESS, // interp
};
#[cfg(target_arch = "x86_64")]
if self.elf_header.get_class() == ExecutableClass::Class32 {
self.add_load_base(load_base_32)?;
} else {
self.add_load_base(load_base)?;
}
#[cfg(not(target_arch = "x86_64"))]
self.add_load_base(load_base)?;
}
if!is_interp {
if let Some(ref mut interp_load_info) = self.interp {
interp_load_info.compute_load_addresses(true)?;
}
}
Ok(())
}
}
#[inline]
fn process_flag<T>(flags: u32, compare_flag: u32, success_flag: T, default_flag: T) -> T {
if flags & compare_flag > 0 {
success_flag
} else {
default_flag
}
}
#[inline]
fn process_prot_flags(flags: u32) -> ProtFlags {
let read_flag = process_flag(flags, PF_R, ProtFlags::PROT_READ, ProtFlags::PROT_NONE);
let write_flag = process_flag(flags, PF_W, ProtFlags::PROT_WRITE, ProtFlags::PROT_NONE);
let execute_flag = process_flag(flags, PF_X, ProtFlags::PROT_EXEC, ProtFlags::PROT_NONE);
read_flag | write_flag | execute_flag
}
#[cfg(test)]
mod tests {
use super::*;
use crate::errors::Error;
use crate::filesystem::FileSystem;
use crate::register::Word;
use crate::utils::tests::get_test_rootfs_path;
use std::path::PathBuf;
#[test]
fn | () {
let rootfs_path = get_test_rootfs_path();
let fs = FileSystem::with_root(rootfs_path).unwrap();
let result = LoadInfo::from(&fs, &PathBuf::from("/../../.."));
assert!(result.is_err());
assert_eq!(Error::errno(EISDIR), result.unwrap_err());
}
#[test]
fn test_load_info_from_path_not_executable() {
let rootfs_path = get_test_rootfs_path();
let fs = FileSystem::with_root(&rootfs_path).unwrap();
let result = LoadInfo::from(&fs, &rootfs_path.join("etc/passwd"));
assert_eq!(Err(Error::errno(ENOEXEC)), result);
}
#[test]
fn test_load_info_from_path_has_mappings() {
let rootfs_path = get_test_rootfs_path();
let fs = FileSystem::with_root(&rootfs_path).unwrap();
let result = LoadInfo::from(&fs, &rootfs_path.join("bin/sleep"));
assert!(result.is_ok());
let load_info = result.unwrap();
assert!(!load_info.mappings.is_empty());
}
#[test]
fn test_load_info_from_path_has_interp() {
let rootfs_path = get_test_rootfs_path();
let fs = FileSystem::with_root(&rootfs_path).unwrap();
let result = LoadInfo::from(&fs, &rootfs_path.join("bin/sleep"));
assert!(result.is_ok());
let load_info = result.unwrap();
assert!(load_info.interp.is_some());
let interp = load_info.interp.unwrap();
assert!(interp.host_path.is_some());
assert!(interp.user_path.is_some());
}
#[test]
#[cfg(all(target_os = "linux", any(target_arch = "x86_64")))]
fn test_load_info_compute_load_addresses() {
let rootfs_path = get_test_rootfs_path();
let fs = FileSystem::with_root(&rootfs_path).unwrap();
let result = LoadInfo::from(&fs, &rootfs_path.join("bin/sleep"));
let load_info = result.unwrap();
let mut interp = load_info.interp.unwrap();
let before_e_entry = get!(interp.elf_header, e_entry, Word).unwrap();
interp.compute_load_addresses(true).unwrap();
let after_e_entry = get!(interp.elf_header, e_entry, Word).unwrap();
assert!(after_e_entry > before_e_entry);
}
}
| test_load_info_from_invalid_path | identifier_name |
load_info.rs | use crate::errors::*;
use crate::filesystem::readers::ExtraReader;
use crate::filesystem::FileSystem;
use crate::filesystem::Translator;
use crate::kernel::execve::binfmt::elf::{ElfHeader, ExecutableClass, ProgramHeader};
use crate::kernel::execve::binfmt::elf::{PF_R, PF_W, PF_X, PT_GNU_STACK, PT_INTERP, PT_LOAD};
use crate::register::Word;
use nix::sys::mman::MapFlags;
use nix::sys::mman::ProtFlags;
use nix::unistd::{sysconf, SysconfVar};
use std::fs::File;
use std::io::{Seek, SeekFrom};
use std::path::{Path, PathBuf};
#[derive(Debug, PartialEq)]
pub struct Mapping {
pub addr: Word,
pub length: Word,
pub clear_length: Word,
pub prot: ProtFlags,
pub flags: MapFlags,
pub fd: Option<Word>,
pub offset: Word,
}
// TODO: redesign this struct and remove unnecessary `Option`
#[derive(Debug, PartialEq)]
pub struct LoadInfo {
pub raw_path: Option<PathBuf>,
pub user_path: Option<PathBuf>,
pub host_path: Option<PathBuf>,
pub elf_header: ElfHeader, | pub needs_executable_stack: bool,
}
lazy_static! {
static ref PAGE_SIZE: Word = match sysconf(SysconfVar::PAGE_SIZE) {
Ok(Some(value)) => value as Word,
_ => 0x1000,
};
static ref PAGE_MASK: Word =!(*PAGE_SIZE - 1);
}
//TODO: move these in arch.rs and do cfg for each env
#[cfg(target_arch = "x86")]
const EXEC_PIC_ADDRESS: Word = 0x0f000000;
#[cfg(target_arch = "x86")]
const INTERP_PIC_ADDRESS: Word = 0xaf000000;
#[cfg(target_arch = "x86_64")]
const EXEC_PIC_ADDRESS: Word = 0x500000000000;
#[cfg(target_arch = "x86_64")]
const INTERP_PIC_ADDRESS: Word = 0x6f0000000000;
#[cfg(target_arch = "x86_64")]
const EXEC_PIC_ADDRESS_32: Word = 0x0f000000;
#[cfg(target_arch = "x86_64")]
const INTERP_PIC_ADDRESS_32: Word = 0xaf000000;
#[cfg(target_arch = "arm")]
const EXEC_PIC_ADDRESS: Word = 0x0f000000;
#[cfg(target_arch = "arm")]
const INTERP_PIC_ADDRESS: Word = 0x1f000000;
#[cfg(target_arch = "aarch64")]
const EXEC_PIC_ADDRESS: Word = 0x3000000000;
#[cfg(target_arch = "aarch64")]
const INTERP_PIC_ADDRESS: Word = 0x3f00000000;
impl LoadInfo {
fn new(elf_header: ElfHeader) -> Self {
Self {
raw_path: None,
user_path: None,
host_path: None,
elf_header: elf_header,
mappings: Vec::new(),
interp: None,
needs_executable_stack: false,
}
}
/// Extracts information about an executable:
/// - the ELF header info
/// - the program header segments, which contain:
/// - mappings
/// - interp???
pub fn from(fs: &FileSystem, host_path: &Path) -> Result<LoadInfo> {
let mut file = File::open(host_path)?;
let (elf_header, mut file) = ElfHeader::extract_from(&mut file)?;
// Sanity checks.
apply!(elf_header, |header| header.is_exec_or_dyn())?;
apply!(elf_header, |header| header.is_known_phentsize())?;
let executable_class = elf_header.get_class();
let program_headers_offset = get!(elf_header, e_phoff, u64)?;
let program_headers_count = get!(elf_header, e_phnum)?;
// We skip the initial part, directly to the program headers.
file.seek(SeekFrom::Start(program_headers_offset))?;
let mut load_info = LoadInfo::new(elf_header);
// We will read all the program headers, and extract info from them.
for _ in 0..program_headers_count {
let program_header = match executable_class {
ExecutableClass::Class32 => ProgramHeader::ProgramHeader32(file.read_struct()?),
ExecutableClass::Class64 => ProgramHeader::ProgramHeader64(file.read_struct()?),
};
let segment_type = get!(program_header, p_type)?;
match segment_type {
// Loadable segment. The bytes from the file are mapped to the beginning of the
// memory segment
PT_LOAD => load_info.add_mapping(&program_header)?,
// Specifies the location and size of a null-terminated path name to invoke as an
// interpreter.
PT_INTERP => load_info.add_interp(fs, &program_header, &mut file)?,
// Check if the stack of this executable file is executable (NX disabled)
PT_GNU_STACK => {
let flags = get!(program_header, p_flags)?;
let prot = process_prot_flags(flags);
load_info.needs_executable_stack = prot.contains(ProtFlags::PROT_EXEC);
}
_ => (),
};
}
Ok(load_info)
}
/// Processes a program header segment into a Mapping,
/// which is then added to the mappings list.
fn add_mapping(&mut self, program_header: &ProgramHeader) -> Result<()> {
let vaddr = get!(program_header, p_vaddr, Word)?;
let memsz = get!(program_header, p_memsz, Word)?;
let filesz = get!(program_header, p_filesz, Word)?;
let offset = get!(program_header, p_offset, Word)?;
let flags = get!(program_header, p_flags)?;
let start_address = vaddr & *PAGE_MASK;
let end_address = (vaddr + filesz + *PAGE_SIZE) & *PAGE_MASK;
let prot = process_prot_flags(flags);
let mut mapping = Mapping {
fd: None, // unknown yet
offset: offset & *PAGE_MASK,
addr: start_address,
// TODO: This can be optimized.
// The calculation of the `length` may be wrong. The field `length` should not be
// calculated using the paged-aligned `end_address`. It will cause more content in the
// target file to be mapped into the memory area. Due to `clear_length`, the
// over-mapped area is later cleared by `clear_length`. However, according to the man
// page of mmap(2), the remaining bytes of a file mapping will be zeroed automatically.
// So the best way is to correct the calculation of `length` and remove `clear_length`
// field.
length: end_address - start_address,
flags: MapFlags::MAP_PRIVATE | MapFlags::MAP_FIXED,
prot: prot,
clear_length: 0,
};
// According to the description in man page elf(5), `p_filesz` may not be larger
// than the `p_memsz`.
// "If the segment's memory size p_memsz is larger than the
// file size p_filesz, the "extra" bytes are defined to hold
// the value 0 and to follow the segment's initialized area."
// -- man 5 elf.
if memsz > filesz {
// How many extra bytes in the current page?
mapping.clear_length = end_address - vaddr - filesz;
self.mappings.push(mapping);
let start_address = end_address;
let end_address = (vaddr + memsz + *PAGE_SIZE) & *PAGE_MASK;
// Create new pages for the remaining extra bytes.
if end_address > start_address {
let new_mapping = Mapping {
fd: None,
offset: 0,
addr: start_address,
length: end_address - start_address,
clear_length: 0,
flags: MapFlags::MAP_PRIVATE | MapFlags::MAP_ANONYMOUS | MapFlags::MAP_FIXED,
prot: prot,
};
self.mappings.push(new_mapping);
}
} else {
self.mappings.push(mapping);
}
Ok(())
}
fn add_interp(
&mut self,
fs: &FileSystem,
program_header: &ProgramHeader,
file: &mut File,
) -> Result<()> {
// Only one PT_INTERP segment is allowed.
if self.interp.is_some() {
return Err(Error::errno_with_msg(
EINVAL,
"when translating execve, double interp",
));
}
let user_path_size = get!(program_header, p_filesz, usize)?;
let user_path_offset = get!(program_header, p_offset, u64)?;
// the -1 is to avoid the null char `\0`
let user_path = file.pread_path_at(user_path_size - 1, user_path_offset)?;
//TODO: implement load info for QEMU
// /* When a QEMU command was specified:
// *
// * - if it's a foreign binary we are reading the ELF
// * interpreter of QEMU instead.
// *
// * - if it's a host binary, we are reading its ELF
// * interpreter.
// *
// * In both case, it lies in "/host-rootfs" from a guest
// * point-of-view. */
// if (tracee->qemu!= NULL && user_path[0] == '/') {
// user_path = talloc_asprintf(tracee->ctx, "%s%s", HOST_ROOTFS,
// user_path); if (user_path == NULL)
// return -ENOMEM;
// }
let host_path = fs.translate_path(&user_path, true)?.1;
FileSystem::check_host_path_executable(&host_path)?;
let mut load_info = LoadInfo::from(fs, &host_path)?;
load_info.host_path = Some(host_path);
load_info.user_path = Some(user_path);
self.interp = Some(Box::new(load_info));
Ok(())
}
/// Add @load_base to each adresses of @load_info.
#[inline]
fn add_load_base(&mut self, load_base: Word) -> Result<()> {
for mapping in &mut self.mappings {
mapping.addr += load_base;
}
self.elf_header.apply_mut(
|mut header32| {
header32.e_entry += load_base as u32;
Ok(())
},
|mut header64| {
header64.e_entry += load_base as u64;
Ok(())
},
)
}
/// Compute the final load address for each position independent objects of
/// @tracee.
pub fn compute_load_addresses(&mut self, is_interp: bool) -> Result<()> {
let is_pos_indep = apply!(self.elf_header, |header| header.is_position_independent())?;
if is_pos_indep && self.mappings.get(0).unwrap().addr == 0 {
#[cfg(target_arch = "x86_64")]
let load_base_32 = match is_interp {
false => EXEC_PIC_ADDRESS_32, // exec
true => INTERP_PIC_ADDRESS_32, // interp
};
let load_base = match is_interp {
false => EXEC_PIC_ADDRESS, // exec
true => INTERP_PIC_ADDRESS, // interp
};
#[cfg(target_arch = "x86_64")]
if self.elf_header.get_class() == ExecutableClass::Class32 {
self.add_load_base(load_base_32)?;
} else {
self.add_load_base(load_base)?;
}
#[cfg(not(target_arch = "x86_64"))]
self.add_load_base(load_base)?;
}
if!is_interp {
if let Some(ref mut interp_load_info) = self.interp {
interp_load_info.compute_load_addresses(true)?;
}
}
Ok(())
}
}
#[inline]
fn process_flag<T>(flags: u32, compare_flag: u32, success_flag: T, default_flag: T) -> T {
if flags & compare_flag > 0 {
success_flag
} else {
default_flag
}
}
#[inline]
fn process_prot_flags(flags: u32) -> ProtFlags {
let read_flag = process_flag(flags, PF_R, ProtFlags::PROT_READ, ProtFlags::PROT_NONE);
let write_flag = process_flag(flags, PF_W, ProtFlags::PROT_WRITE, ProtFlags::PROT_NONE);
let execute_flag = process_flag(flags, PF_X, ProtFlags::PROT_EXEC, ProtFlags::PROT_NONE);
read_flag | write_flag | execute_flag
}
#[cfg(test)]
mod tests {
use super::*;
use crate::errors::Error;
use crate::filesystem::FileSystem;
use crate::register::Word;
use crate::utils::tests::get_test_rootfs_path;
use std::path::PathBuf;
#[test]
fn test_load_info_from_invalid_path() {
let rootfs_path = get_test_rootfs_path();
let fs = FileSystem::with_root(rootfs_path).unwrap();
let result = LoadInfo::from(&fs, &PathBuf::from("/../../.."));
assert!(result.is_err());
assert_eq!(Error::errno(EISDIR), result.unwrap_err());
}
#[test]
fn test_load_info_from_path_not_executable() {
let rootfs_path = get_test_rootfs_path();
let fs = FileSystem::with_root(&rootfs_path).unwrap();
let result = LoadInfo::from(&fs, &rootfs_path.join("etc/passwd"));
assert_eq!(Err(Error::errno(ENOEXEC)), result);
}
#[test]
fn test_load_info_from_path_has_mappings() {
let rootfs_path = get_test_rootfs_path();
let fs = FileSystem::with_root(&rootfs_path).unwrap();
let result = LoadInfo::from(&fs, &rootfs_path.join("bin/sleep"));
assert!(result.is_ok());
let load_info = result.unwrap();
assert!(!load_info.mappings.is_empty());
}
#[test]
fn test_load_info_from_path_has_interp() {
let rootfs_path = get_test_rootfs_path();
let fs = FileSystem::with_root(&rootfs_path).unwrap();
let result = LoadInfo::from(&fs, &rootfs_path.join("bin/sleep"));
assert!(result.is_ok());
let load_info = result.unwrap();
assert!(load_info.interp.is_some());
let interp = load_info.interp.unwrap();
assert!(interp.host_path.is_some());
assert!(interp.user_path.is_some());
}
#[test]
#[cfg(all(target_os = "linux", any(target_arch = "x86_64")))]
fn test_load_info_compute_load_addresses() {
let rootfs_path = get_test_rootfs_path();
let fs = FileSystem::with_root(&rootfs_path).unwrap();
let result = LoadInfo::from(&fs, &rootfs_path.join("bin/sleep"));
let load_info = result.unwrap();
let mut interp = load_info.interp.unwrap();
let before_e_entry = get!(interp.elf_header, e_entry, Word).unwrap();
interp.compute_load_addresses(true).unwrap();
let after_e_entry = get!(interp.elf_header, e_entry, Word).unwrap();
assert!(after_e_entry > before_e_entry);
}
} | pub mappings: Vec<Mapping>,
pub interp: Option<Box<LoadInfo>>, | random_line_split |
load_info.rs | use crate::errors::*;
use crate::filesystem::readers::ExtraReader;
use crate::filesystem::FileSystem;
use crate::filesystem::Translator;
use crate::kernel::execve::binfmt::elf::{ElfHeader, ExecutableClass, ProgramHeader};
use crate::kernel::execve::binfmt::elf::{PF_R, PF_W, PF_X, PT_GNU_STACK, PT_INTERP, PT_LOAD};
use crate::register::Word;
use nix::sys::mman::MapFlags;
use nix::sys::mman::ProtFlags;
use nix::unistd::{sysconf, SysconfVar};
use std::fs::File;
use std::io::{Seek, SeekFrom};
use std::path::{Path, PathBuf};
#[derive(Debug, PartialEq)]
pub struct Mapping {
pub addr: Word,
pub length: Word,
pub clear_length: Word,
pub prot: ProtFlags,
pub flags: MapFlags,
pub fd: Option<Word>,
pub offset: Word,
}
// TODO: redesign this struct and remove unnecessary `Option`
#[derive(Debug, PartialEq)]
pub struct LoadInfo {
pub raw_path: Option<PathBuf>,
pub user_path: Option<PathBuf>,
pub host_path: Option<PathBuf>,
pub elf_header: ElfHeader,
pub mappings: Vec<Mapping>,
pub interp: Option<Box<LoadInfo>>,
pub needs_executable_stack: bool,
}
lazy_static! {
static ref PAGE_SIZE: Word = match sysconf(SysconfVar::PAGE_SIZE) {
Ok(Some(value)) => value as Word,
_ => 0x1000,
};
static ref PAGE_MASK: Word =!(*PAGE_SIZE - 1);
}
//TODO: move these in arch.rs and do cfg for each env
#[cfg(target_arch = "x86")]
const EXEC_PIC_ADDRESS: Word = 0x0f000000;
#[cfg(target_arch = "x86")]
const INTERP_PIC_ADDRESS: Word = 0xaf000000;
#[cfg(target_arch = "x86_64")]
const EXEC_PIC_ADDRESS: Word = 0x500000000000;
#[cfg(target_arch = "x86_64")]
const INTERP_PIC_ADDRESS: Word = 0x6f0000000000;
#[cfg(target_arch = "x86_64")]
const EXEC_PIC_ADDRESS_32: Word = 0x0f000000;
#[cfg(target_arch = "x86_64")]
const INTERP_PIC_ADDRESS_32: Word = 0xaf000000;
#[cfg(target_arch = "arm")]
const EXEC_PIC_ADDRESS: Word = 0x0f000000;
#[cfg(target_arch = "arm")]
const INTERP_PIC_ADDRESS: Word = 0x1f000000;
#[cfg(target_arch = "aarch64")]
const EXEC_PIC_ADDRESS: Word = 0x3000000000;
#[cfg(target_arch = "aarch64")]
const INTERP_PIC_ADDRESS: Word = 0x3f00000000;
impl LoadInfo {
fn new(elf_header: ElfHeader) -> Self {
Self {
raw_path: None,
user_path: None,
host_path: None,
elf_header: elf_header,
mappings: Vec::new(),
interp: None,
needs_executable_stack: false,
}
}
/// Extracts information about an executable:
/// - the ELF header info
/// - the program header segments, which contain:
/// - mappings
/// - interp???
pub fn from(fs: &FileSystem, host_path: &Path) -> Result<LoadInfo> {
let mut file = File::open(host_path)?;
let (elf_header, mut file) = ElfHeader::extract_from(&mut file)?;
// Sanity checks.
apply!(elf_header, |header| header.is_exec_or_dyn())?;
apply!(elf_header, |header| header.is_known_phentsize())?;
let executable_class = elf_header.get_class();
let program_headers_offset = get!(elf_header, e_phoff, u64)?;
let program_headers_count = get!(elf_header, e_phnum)?;
// We skip the initial part, directly to the program headers.
file.seek(SeekFrom::Start(program_headers_offset))?;
let mut load_info = LoadInfo::new(elf_header);
// We will read all the program headers, and extract info from them.
for _ in 0..program_headers_count {
let program_header = match executable_class {
ExecutableClass::Class32 => ProgramHeader::ProgramHeader32(file.read_struct()?),
ExecutableClass::Class64 => ProgramHeader::ProgramHeader64(file.read_struct()?),
};
let segment_type = get!(program_header, p_type)?;
match segment_type {
// Loadable segment. The bytes from the file are mapped to the beginning of the
// memory segment
PT_LOAD => load_info.add_mapping(&program_header)?,
// Specifies the location and size of a null-terminated path name to invoke as an
// interpreter.
PT_INTERP => load_info.add_interp(fs, &program_header, &mut file)?,
// Check if the stack of this executable file is executable (NX disabled)
PT_GNU_STACK => {
let flags = get!(program_header, p_flags)?;
let prot = process_prot_flags(flags);
load_info.needs_executable_stack = prot.contains(ProtFlags::PROT_EXEC);
}
_ => (),
};
}
Ok(load_info)
}
/// Processes a program header segment into a Mapping,
/// which is then added to the mappings list.
fn add_mapping(&mut self, program_header: &ProgramHeader) -> Result<()> {
let vaddr = get!(program_header, p_vaddr, Word)?;
let memsz = get!(program_header, p_memsz, Word)?;
let filesz = get!(program_header, p_filesz, Word)?;
let offset = get!(program_header, p_offset, Word)?;
let flags = get!(program_header, p_flags)?;
let start_address = vaddr & *PAGE_MASK;
let end_address = (vaddr + filesz + *PAGE_SIZE) & *PAGE_MASK;
let prot = process_prot_flags(flags);
let mut mapping = Mapping {
fd: None, // unknown yet
offset: offset & *PAGE_MASK,
addr: start_address,
// TODO: This can be optimized.
// The calculation of the `length` may be wrong. The field `length` should not be
// calculated using the paged-aligned `end_address`. It will cause more content in the
// target file to be mapped into the memory area. Due to `clear_length`, the
// over-mapped area is later cleared by `clear_length`. However, according to the man
// page of mmap(2), the remaining bytes of a file mapping will be zeroed automatically.
// So the best way is to correct the calculation of `length` and remove `clear_length`
// field.
length: end_address - start_address,
flags: MapFlags::MAP_PRIVATE | MapFlags::MAP_FIXED,
prot: prot,
clear_length: 0,
};
// According to the description in man page elf(5), `p_filesz` may not be larger
// than the `p_memsz`.
// "If the segment's memory size p_memsz is larger than the
// file size p_filesz, the "extra" bytes are defined to hold
// the value 0 and to follow the segment's initialized area."
// -- man 5 elf.
if memsz > filesz {
// How many extra bytes in the current page?
mapping.clear_length = end_address - vaddr - filesz;
self.mappings.push(mapping);
let start_address = end_address;
let end_address = (vaddr + memsz + *PAGE_SIZE) & *PAGE_MASK;
// Create new pages for the remaining extra bytes.
if end_address > start_address {
let new_mapping = Mapping {
fd: None,
offset: 0,
addr: start_address,
length: end_address - start_address,
clear_length: 0,
flags: MapFlags::MAP_PRIVATE | MapFlags::MAP_ANONYMOUS | MapFlags::MAP_FIXED,
prot: prot,
};
self.mappings.push(new_mapping);
}
} else {
self.mappings.push(mapping);
}
Ok(())
}
fn add_interp(
&mut self,
fs: &FileSystem,
program_header: &ProgramHeader,
file: &mut File,
) -> Result<()> {
// Only one PT_INTERP segment is allowed.
if self.interp.is_some() {
return Err(Error::errno_with_msg(
EINVAL,
"when translating execve, double interp",
));
}
let user_path_size = get!(program_header, p_filesz, usize)?;
let user_path_offset = get!(program_header, p_offset, u64)?;
// the -1 is to avoid the null char `\0`
let user_path = file.pread_path_at(user_path_size - 1, user_path_offset)?;
//TODO: implement load info for QEMU
// /* When a QEMU command was specified:
// *
// * - if it's a foreign binary we are reading the ELF
// * interpreter of QEMU instead.
// *
// * - if it's a host binary, we are reading its ELF
// * interpreter.
// *
// * In both case, it lies in "/host-rootfs" from a guest
// * point-of-view. */
// if (tracee->qemu!= NULL && user_path[0] == '/') {
// user_path = talloc_asprintf(tracee->ctx, "%s%s", HOST_ROOTFS,
// user_path); if (user_path == NULL)
// return -ENOMEM;
// }
let host_path = fs.translate_path(&user_path, true)?.1;
FileSystem::check_host_path_executable(&host_path)?;
let mut load_info = LoadInfo::from(fs, &host_path)?;
load_info.host_path = Some(host_path);
load_info.user_path = Some(user_path);
self.interp = Some(Box::new(load_info));
Ok(())
}
/// Add @load_base to each adresses of @load_info.
#[inline]
fn add_load_base(&mut self, load_base: Word) -> Result<()> {
for mapping in &mut self.mappings {
mapping.addr += load_base;
}
self.elf_header.apply_mut(
|mut header32| {
header32.e_entry += load_base as u32;
Ok(())
},
|mut header64| {
header64.e_entry += load_base as u64;
Ok(())
},
)
}
/// Compute the final load address for each position independent objects of
/// @tracee.
pub fn compute_load_addresses(&mut self, is_interp: bool) -> Result<()> {
let is_pos_indep = apply!(self.elf_header, |header| header.is_position_independent())?;
if is_pos_indep && self.mappings.get(0).unwrap().addr == 0 {
#[cfg(target_arch = "x86_64")]
let load_base_32 = match is_interp {
false => EXEC_PIC_ADDRESS_32, // exec
true => INTERP_PIC_ADDRESS_32, // interp
};
let load_base = match is_interp {
false => EXEC_PIC_ADDRESS, // exec
true => INTERP_PIC_ADDRESS, // interp
};
#[cfg(target_arch = "x86_64")]
if self.elf_header.get_class() == ExecutableClass::Class32 {
self.add_load_base(load_base_32)?;
} else {
self.add_load_base(load_base)?;
}
#[cfg(not(target_arch = "x86_64"))]
self.add_load_base(load_base)?;
}
if!is_interp {
if let Some(ref mut interp_load_info) = self.interp {
interp_load_info.compute_load_addresses(true)?;
}
}
Ok(())
}
}
#[inline]
fn process_flag<T>(flags: u32, compare_flag: u32, success_flag: T, default_flag: T) -> T |
#[inline]
fn process_prot_flags(flags: u32) -> ProtFlags {
let read_flag = process_flag(flags, PF_R, ProtFlags::PROT_READ, ProtFlags::PROT_NONE);
let write_flag = process_flag(flags, PF_W, ProtFlags::PROT_WRITE, ProtFlags::PROT_NONE);
let execute_flag = process_flag(flags, PF_X, ProtFlags::PROT_EXEC, ProtFlags::PROT_NONE);
read_flag | write_flag | execute_flag
}
#[cfg(test)]
mod tests {
use super::*;
use crate::errors::Error;
use crate::filesystem::FileSystem;
use crate::register::Word;
use crate::utils::tests::get_test_rootfs_path;
use std::path::PathBuf;
#[test]
fn test_load_info_from_invalid_path() {
let rootfs_path = get_test_rootfs_path();
let fs = FileSystem::with_root(rootfs_path).unwrap();
let result = LoadInfo::from(&fs, &PathBuf::from("/../../.."));
assert!(result.is_err());
assert_eq!(Error::errno(EISDIR), result.unwrap_err());
}
#[test]
fn test_load_info_from_path_not_executable() {
let rootfs_path = get_test_rootfs_path();
let fs = FileSystem::with_root(&rootfs_path).unwrap();
let result = LoadInfo::from(&fs, &rootfs_path.join("etc/passwd"));
assert_eq!(Err(Error::errno(ENOEXEC)), result);
}
#[test]
fn test_load_info_from_path_has_mappings() {
let rootfs_path = get_test_rootfs_path();
let fs = FileSystem::with_root(&rootfs_path).unwrap();
let result = LoadInfo::from(&fs, &rootfs_path.join("bin/sleep"));
assert!(result.is_ok());
let load_info = result.unwrap();
assert!(!load_info.mappings.is_empty());
}
#[test]
fn test_load_info_from_path_has_interp() {
let rootfs_path = get_test_rootfs_path();
let fs = FileSystem::with_root(&rootfs_path).unwrap();
let result = LoadInfo::from(&fs, &rootfs_path.join("bin/sleep"));
assert!(result.is_ok());
let load_info = result.unwrap();
assert!(load_info.interp.is_some());
let interp = load_info.interp.unwrap();
assert!(interp.host_path.is_some());
assert!(interp.user_path.is_some());
}
#[test]
#[cfg(all(target_os = "linux", any(target_arch = "x86_64")))]
fn test_load_info_compute_load_addresses() {
let rootfs_path = get_test_rootfs_path();
let fs = FileSystem::with_root(&rootfs_path).unwrap();
let result = LoadInfo::from(&fs, &rootfs_path.join("bin/sleep"));
let load_info = result.unwrap();
let mut interp = load_info.interp.unwrap();
let before_e_entry = get!(interp.elf_header, e_entry, Word).unwrap();
interp.compute_load_addresses(true).unwrap();
let after_e_entry = get!(interp.elf_header, e_entry, Word).unwrap();
assert!(after_e_entry > before_e_entry);
}
}
| {
if flags & compare_flag > 0 {
success_flag
} else {
default_flag
}
} | identifier_body |
emitter.rs | //! An emitter is an instance of geometry that both receives and emits light
//!
//! # Scene Usage Example
//! An emitter is an object in the scene that emits light, it can be a point light
//! or an area light. The emitter takes an extra 'emitter' parameter to specify
//! whether the instance is an area or point emitter and an 'emission' parameter
//! to set the color and strength of emitted light.
//!
//! ## Point Light Example
//! The point light has no geometry, material or transformation since it's not a
//! physical object. Instead it simply takes a position to place the light at in the scene.
//!
//! ```json
//! "objects": [
//! {
//! "name": "my_light",
//! "type": "emitter",
//! "emitter": "point",
//! "position": [0.0, 0.0, 22.0]
//! "emission": [1, 1, 1, 100]
//! },
//! ...
//! ]
//! ```
//!
//! ## Area Light Example
//! The area light looks similar to a regular receiver except it has an additional emission
//! parameter. Area lights are also restricted somewhat in which geometry they can use as
//! it needs to be possible to sample the geometry. Area lights can only accept geometry
//! that implements `geometry::Sampleable`.
//!
//! ```json
//! "objects": [
//! {
//! "name": "my_area_light",
//! "type": "emitter",
//! "emitter": "area",
//! "emission": [1, 1, 1, 100],
//! "material": "white_matte",
//! "geometry": {
//! "type": "sphere",
//! "radius": 2.5
//! },
//! "transform": [
//! {
//! "type": "translate",
//! "translation": [0, 0, 22]
//! }
//! ]
//! },
//! ...
//! ]
//! ```
use std::sync::Arc;
use geometry::{Boundable, BBox, SampleableGeom, DifferentialGeometry};
use material::Material;
use linalg::{self, Transform, Point, Ray, Vector, Normal};
use film::Colorf;
use light::{Light, OcclusionTester};
/// The type of emitter, either a point light or an area light
/// in which case the emitter has associated geometry and a material
/// TODO: Am I happy with this design?
enum EmitterType {
Point,
/// The area light holds the geometry that is emitting the light
/// and the material for the geometry
Area(Arc<SampleableGeom + Send + Sync>, Arc<Material + Send + Sync>),
}
/// An instance of geometry in the scene that receives and emits light.
pub struct Emitter {
emitter: EmitterType,
/// The light intensity emitted
pub emission: Colorf,
/// The transform to world space
transform: Transform,
/// Tag to identify the instance
pub tag: String,
}
impl Emitter {
/// Create a new area light using the geometry passed to emit light
/// TODO: We need sample methods for geometry to do this
/// We also need MIS in the path tracer's direct light sampling so we get
/// good quality
pub fn area(geom: Arc<SampleableGeom + Send + Sync>, material: Arc<Material + Send + Sync>,
emission: Colorf, transform: Transform, tag: String) -> Emitter {
if transform.has_scale() {
println!("Warning: scaling detected in area light transform, this may give incorrect results");
}
Emitter { emitter: EmitterType::Area(geom, material),
emission: emission,
transform: transform,
tag: tag.to_string() }
}
pub fn point(pos: Point, emission: Colorf, tag: String) -> Emitter {
Emitter { emitter: EmitterType::Point,
emission: emission,
transform: Transform::translate(&(pos - Point::broadcast(0.0))),
tag: tag.to_string() }
}
/// Test the ray for intersection against this insance of geometry.
/// returns Some(Intersection) if an intersection was found and None if not.
/// If an intersection is found `ray.max_t` will be set accordingly
pub fn intersect(&self, ray: &mut Ray) -> Option<(DifferentialGeometry, &Material)> {
match &self.emitter {
&EmitterType::Point => None,
&EmitterType::Area(ref geom, ref mat) => {
let mut local = self.transform.inv_mul_ray(ray);
let mut dg = match geom.intersect(&mut local) {
Some(dg) => dg,
None => return None,
};
ray.max_t = local.max_t;
dg.p = self.transform * dg.p;
dg.n = self.transform * dg.n;
dg.ng = self.transform * dg.ng;
dg.dp_du = self.transform * dg.dp_du;
dg.dp_dv = self.transform * dg.dp_dv;
Some((dg, &**mat))
},
}
}
/// Return the radiance emitted by the light in the direction `w`
/// from point `p` on the light's surface with normal `n`
pub fn radiance(&self, w: &Vector, _: &Point, n: &Normal) -> Colorf {
if linalg::dot(w, n) > 0.0 { self.emission } else { Colorf::black() }
}
/// Get the transform to place the emitter into world space
pub fn get_transform(&self) -> &Transform {
return &self.transform;
}
/// Set the transform to place the emitter into world space
pub fn set_transform(&mut self, transform: Transform) {
self.transform = transform;
}
}
impl Boundable for Emitter {
fn bounds(&self) -> BBox {
match &self.emitter {
&EmitterType::Point => BBox::singular(self.transform * Point::broadcast(0.0)),
&EmitterType::Area(ref g, _) => {
self.transform * g.bounds()
},
}
}
}
impl Light for Emitter {
fn sample_incident(&self, p: &Point, samples: &(f32, f32))
-> (Colorf, Vector, f32, OcclusionTester)
{
match &self.emitter {
&EmitterType::Point => {
let pos = self.transform * Point::broadcast(0.0);
let w_i = (pos - *p).normalized();
(self.emission / pos.distance_sqr(p), w_i, 1.0, OcclusionTester::test_points(p, &pos))
}
&EmitterType::Area(ref g, _) => {
let p_l = self.transform.inv_mul_point(p);
let (p_sampled, normal) = g.sample(&p_l, samples);
let w_il = (p_sampled - p_l).normalized();
let pdf = g.pdf(&p_l, &w_il);
let radiance = self.radiance(&-w_il, &p_sampled, &normal);
let p_w = self.transform * p_sampled;
(radiance, self.transform * w_il, pdf, OcclusionTester::test_points(&p, &p_w))
},
}
}
fn | (&self) -> bool {
match &self.emitter {
&EmitterType::Point => true,
_ => false,
}
}
fn pdf(&self, p: &Point, w_i: &Vector) -> f32 {
match &self.emitter {
&EmitterType::Point => 0.0,
&EmitterType::Area(ref g, _ ) => {
let p_l = self.transform.inv_mul_point(p);
let w = (self.transform.inv_mul_vector(w_i)).normalized();
g.pdf(&p_l, &w)
}
}
}
}
| delta_light | identifier_name |
emitter.rs | //! An emitter is an instance of geometry that both receives and emits light
//!
//! # Scene Usage Example
//! An emitter is an object in the scene that emits light, it can be a point light
//! or an area light. The emitter takes an extra 'emitter' parameter to specify
//! whether the instance is an area or point emitter and an 'emission' parameter
//! to set the color and strength of emitted light.
//!
//! ## Point Light Example
//! The point light has no geometry, material or transformation since it's not a
//! physical object. Instead it simply takes a position to place the light at in the scene.
//!
//! ```json
//! "objects": [
//! {
//! "name": "my_light",
//! "type": "emitter",
//! "emitter": "point",
//! "position": [0.0, 0.0, 22.0]
//! "emission": [1, 1, 1, 100]
//! },
//! ...
//! ]
//! ```
//!
//! ## Area Light Example
//! The area light looks similar to a regular receiver except it has an additional emission
//! parameter. Area lights are also restricted somewhat in which geometry they can use as
//! it needs to be possible to sample the geometry. Area lights can only accept geometry
//! that implements `geometry::Sampleable`.
//!
//! ```json
//! "objects": [
//! {
//! "name": "my_area_light",
//! "type": "emitter",
//! "emitter": "area",
//! "emission": [1, 1, 1, 100],
//! "material": "white_matte",
//! "geometry": {
//! "type": "sphere",
//! "radius": 2.5
//! },
//! "transform": [
//! {
//! "type": "translate",
//! "translation": [0, 0, 22]
//! }
//! ]
//! },
//! ...
//! ]
//! ```
use std::sync::Arc;
use geometry::{Boundable, BBox, SampleableGeom, DifferentialGeometry};
use material::Material;
use linalg::{self, Transform, Point, Ray, Vector, Normal};
use film::Colorf;
use light::{Light, OcclusionTester};
/// The type of emitter, either a point light or an area light
/// in which case the emitter has associated geometry and a material
/// TODO: Am I happy with this design?
enum EmitterType {
Point,
/// The area light holds the geometry that is emitting the light
/// and the material for the geometry
Area(Arc<SampleableGeom + Send + Sync>, Arc<Material + Send + Sync>),
}
/// An instance of geometry in the scene that receives and emits light.
pub struct Emitter {
emitter: EmitterType,
/// The light intensity emitted
pub emission: Colorf,
/// The transform to world space
transform: Transform,
/// Tag to identify the instance
pub tag: String,
}
impl Emitter {
/// Create a new area light using the geometry passed to emit light
/// TODO: We need sample methods for geometry to do this
/// We also need MIS in the path tracer's direct light sampling so we get
/// good quality
pub fn area(geom: Arc<SampleableGeom + Send + Sync>, material: Arc<Material + Send + Sync>,
emission: Colorf, transform: Transform, tag: String) -> Emitter {
if transform.has_scale() {
println!("Warning: scaling detected in area light transform, this may give incorrect results");
}
Emitter { emitter: EmitterType::Area(geom, material),
emission: emission,
transform: transform,
tag: tag.to_string() }
}
pub fn point(pos: Point, emission: Colorf, tag: String) -> Emitter {
Emitter { emitter: EmitterType::Point,
emission: emission,
transform: Transform::translate(&(pos - Point::broadcast(0.0))),
tag: tag.to_string() }
}
/// Test the ray for intersection against this insance of geometry.
/// returns Some(Intersection) if an intersection was found and None if not.
/// If an intersection is found `ray.max_t` will be set accordingly
pub fn intersect(&self, ray: &mut Ray) -> Option<(DifferentialGeometry, &Material)> {
match &self.emitter {
&EmitterType::Point => None,
&EmitterType::Area(ref geom, ref mat) => {
let mut local = self.transform.inv_mul_ray(ray);
let mut dg = match geom.intersect(&mut local) {
Some(dg) => dg,
None => return None,
};
ray.max_t = local.max_t;
dg.p = self.transform * dg.p;
dg.n = self.transform * dg.n;
dg.ng = self.transform * dg.ng;
dg.dp_du = self.transform * dg.dp_du;
dg.dp_dv = self.transform * dg.dp_dv;
Some((dg, &**mat))
},
}
}
/// Return the radiance emitted by the light in the direction `w`
/// from point `p` on the light's surface with normal `n`
pub fn radiance(&self, w: &Vector, _: &Point, n: &Normal) -> Colorf {
if linalg::dot(w, n) > 0.0 { self.emission } else { Colorf::black() }
}
/// Get the transform to place the emitter into world space
pub fn get_transform(&self) -> &Transform {
return &self.transform;
}
/// Set the transform to place the emitter into world space
pub fn set_transform(&mut self, transform: Transform) {
self.transform = transform;
}
}
impl Boundable for Emitter {
fn bounds(&self) -> BBox {
match &self.emitter {
&EmitterType::Point => BBox::singular(self.transform * Point::broadcast(0.0)),
&EmitterType::Area(ref g, _) => {
self.transform * g.bounds()
},
}
}
}
impl Light for Emitter {
fn sample_incident(&self, p: &Point, samples: &(f32, f32))
-> (Colorf, Vector, f32, OcclusionTester)
{
match &self.emitter {
&EmitterType::Point => {
let pos = self.transform * Point::broadcast(0.0);
let w_i = (pos - *p).normalized();
(self.emission / pos.distance_sqr(p), w_i, 1.0, OcclusionTester::test_points(p, &pos))
}
&EmitterType::Area(ref g, _) => {
let p_l = self.transform.inv_mul_point(p);
let (p_sampled, normal) = g.sample(&p_l, samples);
let w_il = (p_sampled - p_l).normalized();
let pdf = g.pdf(&p_l, &w_il);
let radiance = self.radiance(&-w_il, &p_sampled, &normal);
let p_w = self.transform * p_sampled;
(radiance, self.transform * w_il, pdf, OcclusionTester::test_points(&p, &p_w))
},
}
}
fn delta_light(&self) -> bool {
match &self.emitter {
&EmitterType::Point => true,
_ => false,
}
}
fn pdf(&self, p: &Point, w_i: &Vector) -> f32 {
match &self.emitter {
&EmitterType::Point => 0.0,
&EmitterType::Area(ref g, _ ) => { | let w = (self.transform.inv_mul_vector(w_i)).normalized();
g.pdf(&p_l, &w)
}
}
}
} | let p_l = self.transform.inv_mul_point(p); | random_line_split |
emitter.rs | //! An emitter is an instance of geometry that both receives and emits light
//!
//! # Scene Usage Example
//! An emitter is an object in the scene that emits light, it can be a point light
//! or an area light. The emitter takes an extra 'emitter' parameter to specify
//! whether the instance is an area or point emitter and an 'emission' parameter
//! to set the color and strength of emitted light.
//!
//! ## Point Light Example
//! The point light has no geometry, material or transformation since it's not a
//! physical object. Instead it simply takes a position to place the light at in the scene.
//!
//! ```json
//! "objects": [
//! {
//! "name": "my_light",
//! "type": "emitter",
//! "emitter": "point",
//! "position": [0.0, 0.0, 22.0]
//! "emission": [1, 1, 1, 100]
//! },
//! ...
//! ]
//! ```
//!
//! ## Area Light Example
//! The area light looks similar to a regular receiver except it has an additional emission
//! parameter. Area lights are also restricted somewhat in which geometry they can use as
//! it needs to be possible to sample the geometry. Area lights can only accept geometry
//! that implements `geometry::Sampleable`.
//!
//! ```json
//! "objects": [
//! {
//! "name": "my_area_light",
//! "type": "emitter",
//! "emitter": "area",
//! "emission": [1, 1, 1, 100],
//! "material": "white_matte",
//! "geometry": {
//! "type": "sphere",
//! "radius": 2.5
//! },
//! "transform": [
//! {
//! "type": "translate",
//! "translation": [0, 0, 22]
//! }
//! ]
//! },
//! ...
//! ]
//! ```
use std::sync::Arc;
use geometry::{Boundable, BBox, SampleableGeom, DifferentialGeometry};
use material::Material;
use linalg::{self, Transform, Point, Ray, Vector, Normal};
use film::Colorf;
use light::{Light, OcclusionTester};
/// The type of emitter, either a point light or an area light
/// in which case the emitter has associated geometry and a material
/// TODO: Am I happy with this design?
enum EmitterType {
Point,
/// The area light holds the geometry that is emitting the light
/// and the material for the geometry
Area(Arc<SampleableGeom + Send + Sync>, Arc<Material + Send + Sync>),
}
/// An instance of geometry in the scene that receives and emits light.
pub struct Emitter {
emitter: EmitterType,
/// The light intensity emitted
pub emission: Colorf,
/// The transform to world space
transform: Transform,
/// Tag to identify the instance
pub tag: String,
}
impl Emitter {
/// Create a new area light using the geometry passed to emit light
/// TODO: We need sample methods for geometry to do this
/// We also need MIS in the path tracer's direct light sampling so we get
/// good quality
pub fn area(geom: Arc<SampleableGeom + Send + Sync>, material: Arc<Material + Send + Sync>,
emission: Colorf, transform: Transform, tag: String) -> Emitter {
if transform.has_scale() {
println!("Warning: scaling detected in area light transform, this may give incorrect results");
}
Emitter { emitter: EmitterType::Area(geom, material),
emission: emission,
transform: transform,
tag: tag.to_string() }
}
pub fn point(pos: Point, emission: Colorf, tag: String) -> Emitter {
Emitter { emitter: EmitterType::Point,
emission: emission,
transform: Transform::translate(&(pos - Point::broadcast(0.0))),
tag: tag.to_string() }
}
/// Test the ray for intersection against this insance of geometry.
/// returns Some(Intersection) if an intersection was found and None if not.
/// If an intersection is found `ray.max_t` will be set accordingly
pub fn intersect(&self, ray: &mut Ray) -> Option<(DifferentialGeometry, &Material)> {
match &self.emitter {
&EmitterType::Point => None,
&EmitterType::Area(ref geom, ref mat) => {
let mut local = self.transform.inv_mul_ray(ray);
let mut dg = match geom.intersect(&mut local) {
Some(dg) => dg,
None => return None,
};
ray.max_t = local.max_t;
dg.p = self.transform * dg.p;
dg.n = self.transform * dg.n;
dg.ng = self.transform * dg.ng;
dg.dp_du = self.transform * dg.dp_du;
dg.dp_dv = self.transform * dg.dp_dv;
Some((dg, &**mat))
},
}
}
/// Return the radiance emitted by the light in the direction `w`
/// from point `p` on the light's surface with normal `n`
pub fn radiance(&self, w: &Vector, _: &Point, n: &Normal) -> Colorf {
if linalg::dot(w, n) > 0.0 { self.emission } else { Colorf::black() }
}
/// Get the transform to place the emitter into world space
pub fn get_transform(&self) -> &Transform {
return &self.transform;
}
/// Set the transform to place the emitter into world space
pub fn set_transform(&mut self, transform: Transform) {
self.transform = transform;
}
}
impl Boundable for Emitter {
fn bounds(&self) -> BBox |
}
impl Light for Emitter {
fn sample_incident(&self, p: &Point, samples: &(f32, f32))
-> (Colorf, Vector, f32, OcclusionTester)
{
match &self.emitter {
&EmitterType::Point => {
let pos = self.transform * Point::broadcast(0.0);
let w_i = (pos - *p).normalized();
(self.emission / pos.distance_sqr(p), w_i, 1.0, OcclusionTester::test_points(p, &pos))
}
&EmitterType::Area(ref g, _) => {
let p_l = self.transform.inv_mul_point(p);
let (p_sampled, normal) = g.sample(&p_l, samples);
let w_il = (p_sampled - p_l).normalized();
let pdf = g.pdf(&p_l, &w_il);
let radiance = self.radiance(&-w_il, &p_sampled, &normal);
let p_w = self.transform * p_sampled;
(radiance, self.transform * w_il, pdf, OcclusionTester::test_points(&p, &p_w))
},
}
}
fn delta_light(&self) -> bool {
match &self.emitter {
&EmitterType::Point => true,
_ => false,
}
}
fn pdf(&self, p: &Point, w_i: &Vector) -> f32 {
match &self.emitter {
&EmitterType::Point => 0.0,
&EmitterType::Area(ref g, _ ) => {
let p_l = self.transform.inv_mul_point(p);
let w = (self.transform.inv_mul_vector(w_i)).normalized();
g.pdf(&p_l, &w)
}
}
}
}
| {
match &self.emitter {
&EmitterType::Point => BBox::singular(self.transform * Point::broadcast(0.0)),
&EmitterType::Area(ref g, _) => {
self.transform * g.bounds()
},
}
} | identifier_body |
receive_as_stream.rs | // Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
use super::*;
use futures::task::Context;
use futures::task::Poll;
use std::pin::Pin;
/// A [`Stream`] that is created by [`LocalEndpointExt::receive_as_stream`].
///
/// [`Stream`]: futures::stream::Stream
/// [`LocalEndpointExt::receive_as_stream`]: crate::LocalEndpointExt::receive_as_stream
pub struct ReceiveAsStream<'a, LE, F> {
local_endpoint: &'a LE,
handler: F,
recv_future: Option<BoxFuture<'a, Result<(), Error>>>,
}
impl<'a, LE: core::fmt::Debug, F: core::fmt::Debug> core::fmt::Debug
for ReceiveAsStream<'a, LE, F>
{
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
f.debug_struct("ReceiveAsStream")
.field("local_endpoint", self.local_endpoint)
.field("handler", &self.handler)
.field("recv_future", &self.recv_future.as_ref().map(|_| ""))
.finish()
}
}
impl<'a, LE, F> ReceiveAsStream<'a, LE, F>
where
LE: LocalEndpoint,
F: FnMut(&LE::RespondableInboundContext) -> Result<(), Error> + 'a + Clone + Unpin + Send,
{
pub(crate) fn new(local_endpoint: &'a LE, handler: F) -> ReceiveAsStream<'a, LE, F> {
let mut ret = ReceiveAsStream {
local_endpoint,
recv_future: None,
handler,
};
ret.update_recv_future();
return ret;
}
fn update_recv_future(&mut self) |
fn _poll_next_unpin(&mut self, cx: &mut Context<'_>) -> Poll<Option<Result<(), Error>>> {
if let Some(recv_future) = self.recv_future.as_mut() {
match recv_future.poll_unpin(cx) {
Poll::Ready(Err(Error::IOError)) => {
self.recv_future = None;
Poll::Ready(Some(Err(Error::IOError)))
}
Poll::Ready(Err(Error::Cancelled)) => {
self.recv_future = None;
Poll::Ready(Some(Err(Error::Cancelled)))
}
Poll::Ready(_) => {
self.update_recv_future();
Poll::Ready(Some(Ok(())))
}
Poll::Pending => Poll::Pending,
}
} else {
Poll::Ready(None)
}
}
}
impl<'a, LE, F> Stream for ReceiveAsStream<'a, LE, F>
where
LE: LocalEndpoint,
F: FnMut(&LE::RespondableInboundContext) -> Result<(), Error> + 'a + Clone + Unpin + Send,
{
type Item = Result<(), Error>;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
self.get_mut()._poll_next_unpin(cx)
}
}
| {
self.recv_future = Some(self.local_endpoint.receive(self.handler.clone()));
} | identifier_body |
receive_as_stream.rs | // Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
use super::*;
use futures::task::Context;
use futures::task::Poll;
use std::pin::Pin;
/// A [`Stream`] that is created by [`LocalEndpointExt::receive_as_stream`].
///
/// [`Stream`]: futures::stream::Stream
/// [`LocalEndpointExt::receive_as_stream`]: crate::LocalEndpointExt::receive_as_stream
pub struct ReceiveAsStream<'a, LE, F> {
local_endpoint: &'a LE,
handler: F,
recv_future: Option<BoxFuture<'a, Result<(), Error>>>,
}
impl<'a, LE: core::fmt::Debug, F: core::fmt::Debug> core::fmt::Debug
for ReceiveAsStream<'a, LE, F>
{
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
f.debug_struct("ReceiveAsStream")
.field("local_endpoint", self.local_endpoint)
.field("handler", &self.handler)
.field("recv_future", &self.recv_future.as_ref().map(|_| ""))
.finish()
}
}
impl<'a, LE, F> ReceiveAsStream<'a, LE, F>
where
LE: LocalEndpoint,
F: FnMut(&LE::RespondableInboundContext) -> Result<(), Error> + 'a + Clone + Unpin + Send,
{
pub(crate) fn new(local_endpoint: &'a LE, handler: F) -> ReceiveAsStream<'a, LE, F> {
let mut ret = ReceiveAsStream {
local_endpoint,
recv_future: None,
handler,
};
ret.update_recv_future();
return ret;
}
fn update_recv_future(&mut self) {
self.recv_future = Some(self.local_endpoint.receive(self.handler.clone()));
}
fn _poll_next_unpin(&mut self, cx: &mut Context<'_>) -> Poll<Option<Result<(), Error>>> {
if let Some(recv_future) = self.recv_future.as_mut() {
match recv_future.poll_unpin(cx) {
Poll::Ready(Err(Error::IOError)) => {
self.recv_future = None;
Poll::Ready(Some(Err(Error::IOError)))
}
Poll::Ready(Err(Error::Cancelled)) => {
self.recv_future = None;
Poll::Ready(Some(Err(Error::Cancelled)))
}
Poll::Ready(_) => {
self.update_recv_future();
Poll::Ready(Some(Ok(())))
}
Poll::Pending => Poll::Pending,
}
} else {
Poll::Ready(None)
}
}
}
impl<'a, LE, F> Stream for ReceiveAsStream<'a, LE, F>
where
LE: LocalEndpoint,
F: FnMut(&LE::RespondableInboundContext) -> Result<(), Error> + 'a + Clone + Unpin + Send,
{ | } | type Item = Result<(), Error>;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
self.get_mut()._poll_next_unpin(cx)
} | random_line_split |
receive_as_stream.rs | // Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
use super::*;
use futures::task::Context;
use futures::task::Poll;
use std::pin::Pin;
/// A [`Stream`] that is created by [`LocalEndpointExt::receive_as_stream`].
///
/// [`Stream`]: futures::stream::Stream
/// [`LocalEndpointExt::receive_as_stream`]: crate::LocalEndpointExt::receive_as_stream
pub struct ReceiveAsStream<'a, LE, F> {
local_endpoint: &'a LE,
handler: F,
recv_future: Option<BoxFuture<'a, Result<(), Error>>>,
}
impl<'a, LE: core::fmt::Debug, F: core::fmt::Debug> core::fmt::Debug
for ReceiveAsStream<'a, LE, F>
{
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
f.debug_struct("ReceiveAsStream")
.field("local_endpoint", self.local_endpoint)
.field("handler", &self.handler)
.field("recv_future", &self.recv_future.as_ref().map(|_| ""))
.finish()
}
}
impl<'a, LE, F> ReceiveAsStream<'a, LE, F>
where
LE: LocalEndpoint,
F: FnMut(&LE::RespondableInboundContext) -> Result<(), Error> + 'a + Clone + Unpin + Send,
{
pub(crate) fn | (local_endpoint: &'a LE, handler: F) -> ReceiveAsStream<'a, LE, F> {
let mut ret = ReceiveAsStream {
local_endpoint,
recv_future: None,
handler,
};
ret.update_recv_future();
return ret;
}
fn update_recv_future(&mut self) {
self.recv_future = Some(self.local_endpoint.receive(self.handler.clone()));
}
fn _poll_next_unpin(&mut self, cx: &mut Context<'_>) -> Poll<Option<Result<(), Error>>> {
if let Some(recv_future) = self.recv_future.as_mut() {
match recv_future.poll_unpin(cx) {
Poll::Ready(Err(Error::IOError)) => {
self.recv_future = None;
Poll::Ready(Some(Err(Error::IOError)))
}
Poll::Ready(Err(Error::Cancelled)) => {
self.recv_future = None;
Poll::Ready(Some(Err(Error::Cancelled)))
}
Poll::Ready(_) => {
self.update_recv_future();
Poll::Ready(Some(Ok(())))
}
Poll::Pending => Poll::Pending,
}
} else {
Poll::Ready(None)
}
}
}
impl<'a, LE, F> Stream for ReceiveAsStream<'a, LE, F>
where
LE: LocalEndpoint,
F: FnMut(&LE::RespondableInboundContext) -> Result<(), Error> + 'a + Clone + Unpin + Send,
{
type Item = Result<(), Error>;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
self.get_mut()._poll_next_unpin(cx)
}
}
| new | identifier_name |
eo_view.rs |
// std imports
use std::mem;
// external imports
use num::traits::Num;
// local imports
use algebra::structure::MagmaBase;
use super::eo_traits::{ERO, ECO};
use matrix::view::MatrixView;
use matrix::traits::{Shape, MatrixBuffer, Strided};
/// Implementation of Elementary row operations.
impl<'a, T:MagmaBase + Num> ERO<T> for MatrixView<'a, T> {
/// Row scaling by a factor and adding to another row.
/// r_i = r_i + k * r_j
/// The j-th row can be outside the view also.
/// This is the row relative to the start of the view.
#[inline]
fn ero_scale_add(&mut self,
i : usize,
j : isize,
scale : T
)-> &mut MatrixView<'a, T> {
debug_assert! (i < self.num_rows());
let m = self.matrix();
// Compute j-th row in m (by doing offset)
let j = j + (self.start_row() as isize);
debug_assert! (j >= 0);
let j = j as usize;
debug_assert!(j < m.num_rows());
let ptr = m.as_ptr();
// I am allowing modification of the underlying buffer
let ptr : *mut T = unsafe { mem::transmute(ptr) };
let sc = self.start_col();
// Compute initial offsets
let mut offset_a = self.cell_to_offset(i, 0);
let mut offset_b = m.cell_to_offset(j, sc);
let stride_a = self.stride() as isize;
let stride_b = m.stride() as isize;
for _ in 0..self.num_cols(){
unsafe {
let va = *ptr.offset(offset_a);
let vb = *ptr.offset(offset_b);
*ptr.offset(offset_a) = va + scale * vb;
}
// Update offsets
offset_a += stride_a;
offset_b += stride_b;
}
self
}
}
/// Implementation of Elementary column operations.
impl<'a, T:MagmaBase + Num> ECO<T> for MatrixView<'a, T> {
/// Column scaling by a factor and adding to another column.
/// c_i = c_i + k * c_j
/// The j-th column can be outside the view also.
/// This is the column relative to the start of the view.
#[inline]
fn | (&mut self,
i : usize,
j : isize,
scale : T
)-> &mut MatrixView<'a, T> {
debug_assert! (i < self.num_cols());
let m = self.matrix();
// Compute j-th column in m (by doing offset)
let j = j + (self.start_col() as isize);
debug_assert! (j >= 0);
let j = j as usize;
debug_assert!(j < m.num_cols());
let ptr = m.as_ptr();
// I am allowing modification of the underlying buffer
let ptr : *mut T = unsafe { mem::transmute(ptr) };
let sr = self.start_row();
// Compute initial offsets
let mut offset_a = self.cell_to_offset(0, i);
let mut offset_b = m.cell_to_offset(sr, j);
for _ in 0..self.num_rows(){
unsafe {
let va = *ptr.offset(offset_a);
let vb = *ptr.offset(offset_b);
*ptr.offset(offset_a) = va + scale * vb;
}
// Update offsets
offset_a += 1;
offset_b += 1;
}
self
}
}
/******************************************************
*
* Unit tests
*
*******************************************************/
#[cfg(test)]
mod test{
//use super::*;
}
/******************************************************
*
* Bench marks
*
*******************************************************/
#[cfg(test)]
mod bench{
//extern crate test;
//use self::test::Bencher;
//use super::*;
}
| eco_scale_add | identifier_name |
eo_view.rs |
// std imports
use std::mem;
// external imports
use num::traits::Num;
// local imports
use algebra::structure::MagmaBase;
use super::eo_traits::{ERO, ECO};
use matrix::view::MatrixView;
use matrix::traits::{Shape, MatrixBuffer, Strided};
/// Implementation of Elementary row operations.
impl<'a, T:MagmaBase + Num> ERO<T> for MatrixView<'a, T> {
/// Row scaling by a factor and adding to another row.
/// r_i = r_i + k * r_j
/// The j-th row can be outside the view also.
/// This is the row relative to the start of the view.
#[inline]
fn ero_scale_add(&mut self,
i : usize,
j : isize,
scale : T
)-> &mut MatrixView<'a, T> {
debug_assert! (i < self.num_rows());
let m = self.matrix();
// Compute j-th row in m (by doing offset)
let j = j + (self.start_row() as isize);
debug_assert! (j >= 0);
let j = j as usize;
debug_assert!(j < m.num_rows());
let ptr = m.as_ptr();
// I am allowing modification of the underlying buffer
let ptr : *mut T = unsafe { mem::transmute(ptr) };
let sc = self.start_col();
// Compute initial offsets
let mut offset_a = self.cell_to_offset(i, 0);
let mut offset_b = m.cell_to_offset(j, sc);
let stride_a = self.stride() as isize;
let stride_b = m.stride() as isize;
for _ in 0..self.num_cols(){
unsafe {
let va = *ptr.offset(offset_a);
let vb = *ptr.offset(offset_b);
*ptr.offset(offset_a) = va + scale * vb;
}
// Update offsets
offset_a += stride_a;
offset_b += stride_b;
}
self
}
}
/// Implementation of Elementary column operations.
impl<'a, T:MagmaBase + Num> ECO<T> for MatrixView<'a, T> {
/// Column scaling by a factor and adding to another column.
/// c_i = c_i + k * c_j
/// The j-th column can be outside the view also.
/// This is the column relative to the start of the view.
#[inline]
fn eco_scale_add(&mut self,
i : usize,
j : isize,
scale : T
)-> &mut MatrixView<'a, T> | }
// Update offsets
offset_a += 1;
offset_b += 1;
}
self
}
}
/******************************************************
*
* Unit tests
*
*******************************************************/
#[cfg(test)]
mod test{
//use super::*;
}
/******************************************************
*
* Bench marks
*
*******************************************************/
#[cfg(test)]
mod bench{
//extern crate test;
//use self::test::Bencher;
//use super::*;
}
| {
debug_assert! (i < self.num_cols());
let m = self.matrix();
// Compute j-th column in m (by doing offset)
let j = j + (self.start_col() as isize);
debug_assert! (j >= 0);
let j = j as usize;
debug_assert!(j < m.num_cols());
let ptr = m.as_ptr();
// I am allowing modification of the underlying buffer
let ptr : *mut T = unsafe { mem::transmute(ptr) };
let sr = self.start_row();
// Compute initial offsets
let mut offset_a = self.cell_to_offset(0, i);
let mut offset_b = m.cell_to_offset(sr, j);
for _ in 0..self.num_rows(){
unsafe {
let va = *ptr.offset(offset_a);
let vb = *ptr.offset(offset_b);
*ptr.offset(offset_a) = va + scale * vb; | identifier_body |
eo_view.rs | // std imports
use std::mem;
// external imports
use num::traits::Num;
| // local imports
use algebra::structure::MagmaBase;
use super::eo_traits::{ERO, ECO};
use matrix::view::MatrixView;
use matrix::traits::{Shape, MatrixBuffer, Strided};
/// Implementation of Elementary row operations.
impl<'a, T:MagmaBase + Num> ERO<T> for MatrixView<'a, T> {
/// Row scaling by a factor and adding to another row.
/// r_i = r_i + k * r_j
/// The j-th row can be outside the view also.
/// This is the row relative to the start of the view.
#[inline]
fn ero_scale_add(&mut self,
i : usize,
j : isize,
scale : T
)-> &mut MatrixView<'a, T> {
debug_assert! (i < self.num_rows());
let m = self.matrix();
// Compute j-th row in m (by doing offset)
let j = j + (self.start_row() as isize);
debug_assert! (j >= 0);
let j = j as usize;
debug_assert!(j < m.num_rows());
let ptr = m.as_ptr();
// I am allowing modification of the underlying buffer
let ptr : *mut T = unsafe { mem::transmute(ptr) };
let sc = self.start_col();
// Compute initial offsets
let mut offset_a = self.cell_to_offset(i, 0);
let mut offset_b = m.cell_to_offset(j, sc);
let stride_a = self.stride() as isize;
let stride_b = m.stride() as isize;
for _ in 0..self.num_cols(){
unsafe {
let va = *ptr.offset(offset_a);
let vb = *ptr.offset(offset_b);
*ptr.offset(offset_a) = va + scale * vb;
}
// Update offsets
offset_a += stride_a;
offset_b += stride_b;
}
self
}
}
/// Implementation of Elementary column operations.
impl<'a, T:MagmaBase + Num> ECO<T> for MatrixView<'a, T> {
/// Column scaling by a factor and adding to another column.
/// c_i = c_i + k * c_j
/// The j-th column can be outside the view also.
/// This is the column relative to the start of the view.
#[inline]
fn eco_scale_add(&mut self,
i : usize,
j : isize,
scale : T
)-> &mut MatrixView<'a, T> {
debug_assert! (i < self.num_cols());
let m = self.matrix();
// Compute j-th column in m (by doing offset)
let j = j + (self.start_col() as isize);
debug_assert! (j >= 0);
let j = j as usize;
debug_assert!(j < m.num_cols());
let ptr = m.as_ptr();
// I am allowing modification of the underlying buffer
let ptr : *mut T = unsafe { mem::transmute(ptr) };
let sr = self.start_row();
// Compute initial offsets
let mut offset_a = self.cell_to_offset(0, i);
let mut offset_b = m.cell_to_offset(sr, j);
for _ in 0..self.num_rows(){
unsafe {
let va = *ptr.offset(offset_a);
let vb = *ptr.offset(offset_b);
*ptr.offset(offset_a) = va + scale * vb;
}
// Update offsets
offset_a += 1;
offset_b += 1;
}
self
}
}
/******************************************************
*
* Unit tests
*
*******************************************************/
#[cfg(test)]
mod test{
//use super::*;
}
/******************************************************
*
* Bench marks
*
*******************************************************/
#[cfg(test)]
mod bench{
//extern crate test;
//use self::test::Bencher;
//use super::*;
} | random_line_split | |
borrowck-lend-flow.rs | // Copyright 2012 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.
// Note: the borrowck analysis is currently flow-insensitive.
// Therefore, some of these errors are marked as spurious and could be
// corrected by a simple change to the analysis. The others are
// either genuine or would require more advanced changes. The latter
// cases are noted.
#![feature(box_syntax)]
fn borrow(_v: &isize) {}
fn borrow_mut(_v: &mut isize) {}
fn cond() -> bool { panic!() }
fn for_func<F>(_f: F) where F: FnOnce() -> bool |
fn produce<T>() -> T { panic!(); }
fn inc(v: &mut Box<isize>) {
*v = box (**v + 1);
}
fn pre_freeze() {
// In this instance, the freeze starts before the mut borrow.
let mut v: Box<_> = box 3;
let _w = &v;
borrow_mut(&mut *v); //~ ERROR cannot borrow
_w.use_ref();
}
fn post_freeze() {
// In this instance, the const alias starts after the borrow.
let mut v: Box<_> = box 3;
borrow_mut(&mut *v);
let _w = &v;
}
fn main() {}
trait Fake { fn use_mut(&mut self) { } fn use_ref(&self) { } }
impl<T> Fake for T { }
| { panic!() } | identifier_body |
borrowck-lend-flow.rs | // Copyright 2012 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.
// Note: the borrowck analysis is currently flow-insensitive.
// Therefore, some of these errors are marked as spurious and could be
// corrected by a simple change to the analysis. The others are
// either genuine or would require more advanced changes. The latter
// cases are noted.
#![feature(box_syntax)]
fn borrow(_v: &isize) {}
fn borrow_mut(_v: &mut isize) {}
fn cond() -> bool { panic!() }
fn for_func<F>(_f: F) where F: FnOnce() -> bool { panic!() }
fn produce<T>() -> T { panic!(); }
fn inc(v: &mut Box<isize>) {
*v = box (**v + 1);
}
fn pre_freeze() {
// In this instance, the freeze starts before the mut borrow.
let mut v: Box<_> = box 3;
let _w = &v;
borrow_mut(&mut *v); //~ ERROR cannot borrow
_w.use_ref();
}
fn | () {
// In this instance, the const alias starts after the borrow.
let mut v: Box<_> = box 3;
borrow_mut(&mut *v);
let _w = &v;
}
fn main() {}
trait Fake { fn use_mut(&mut self) { } fn use_ref(&self) { } }
impl<T> Fake for T { }
| post_freeze | identifier_name |
borrowck-lend-flow.rs | // Copyright 2012 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.
// Note: the borrowck analysis is currently flow-insensitive.
// Therefore, some of these errors are marked as spurious and could be
// corrected by a simple change to the analysis. The others are | // either genuine or would require more advanced changes. The latter
// cases are noted.
#![feature(box_syntax)]
fn borrow(_v: &isize) {}
fn borrow_mut(_v: &mut isize) {}
fn cond() -> bool { panic!() }
fn for_func<F>(_f: F) where F: FnOnce() -> bool { panic!() }
fn produce<T>() -> T { panic!(); }
fn inc(v: &mut Box<isize>) {
*v = box (**v + 1);
}
fn pre_freeze() {
// In this instance, the freeze starts before the mut borrow.
let mut v: Box<_> = box 3;
let _w = &v;
borrow_mut(&mut *v); //~ ERROR cannot borrow
_w.use_ref();
}
fn post_freeze() {
// In this instance, the const alias starts after the borrow.
let mut v: Box<_> = box 3;
borrow_mut(&mut *v);
let _w = &v;
}
fn main() {}
trait Fake { fn use_mut(&mut self) { } fn use_ref(&self) { } }
impl<T> Fake for T { } | random_line_split | |
utils.rs | //! Various utilities
/*
use std::old_io::net::ip;
/// Convert socket address to bytes in network order.
pub fn netaddr_to_netbytes(addr: &ip::SocketAddr) -> Vec<u8> {
match addr.ip {
ip::Ipv4Addr(a, b, c, d) =>
vec![a, b, c, d, (addr.port >> 8) as u8, (addr.port & 0xFF) as u8],
// TODO(divius): implement
ip::Ipv6Addr(..) => panic!("IPv6 not implemented")
}
}
/// Get socket address from netbytes.
pub fn netaddr_from_netbytes(bytes: &[u8]) -> ip::SocketAddr {
assert_eq!(6, bytes.len());
ip::SocketAddr {
ip: ip::Ipv4Addr(bytes[0], bytes[1], bytes[2], bytes[3]),
port: ((bytes[4] as u16) << 8) + bytes[5] as u16
}
}
*/
#[cfg(test)]
pub mod test {
use std::net::SocketAddr;
use std::net::SocketAddrV4;
use std::net::Ipv4Addr;
use num::traits::FromPrimitive;
use num;
use super::super::Node;
pub static ADDR: &'static str = "127.0.0.1:8008";
pub fn new_node(id: usize) -> Node {
new_node_with_port(id, 8008)
}
pub fn new_node_with_port(id: usize, port: u16) -> Node {
Node {
id: FromPrimitive::from_usize(id).unwrap(),
address: SocketAddr::V4( SocketAddrV4::new(
Ipv4Addr::new(127, 0, 0, 1),
port
) )
}
}
pub fn | (id: usize) -> num::BigUint {
FromPrimitive::from_usize(id).unwrap()
}
}
| usize_to_id | identifier_name |
utils.rs | //! Various utilities
/*
use std::old_io::net::ip;
/// Convert socket address to bytes in network order.
pub fn netaddr_to_netbytes(addr: &ip::SocketAddr) -> Vec<u8> {
match addr.ip {
ip::Ipv4Addr(a, b, c, d) =>
vec![a, b, c, d, (addr.port >> 8) as u8, (addr.port & 0xFF) as u8],
// TODO(divius): implement
ip::Ipv6Addr(..) => panic!("IPv6 not implemented")
}
}
/// Get socket address from netbytes.
pub fn netaddr_from_netbytes(bytes: &[u8]) -> ip::SocketAddr {
assert_eq!(6, bytes.len());
ip::SocketAddr {
ip: ip::Ipv4Addr(bytes[0], bytes[1], bytes[2], bytes[3]),
port: ((bytes[4] as u16) << 8) + bytes[5] as u16
}
}
*/
#[cfg(test)]
pub mod test {
use std::net::SocketAddr;
use std::net::SocketAddrV4;
use std::net::Ipv4Addr;
use num::traits::FromPrimitive;
use num;
use super::super::Node;
pub static ADDR: &'static str = "127.0.0.1:8008";
pub fn new_node(id: usize) -> Node |
pub fn new_node_with_port(id: usize, port: u16) -> Node {
Node {
id: FromPrimitive::from_usize(id).unwrap(),
address: SocketAddr::V4( SocketAddrV4::new(
Ipv4Addr::new(127, 0, 0, 1),
port
) )
}
}
pub fn usize_to_id(id: usize) -> num::BigUint {
FromPrimitive::from_usize(id).unwrap()
}
}
| {
new_node_with_port(id, 8008)
} | identifier_body |
utils.rs | //! Various utilities
/*
use std::old_io::net::ip;
/// Convert socket address to bytes in network order.
pub fn netaddr_to_netbytes(addr: &ip::SocketAddr) -> Vec<u8> {
match addr.ip {
ip::Ipv4Addr(a, b, c, d) =>
vec![a, b, c, d, (addr.port >> 8) as u8, (addr.port & 0xFF) as u8],
// TODO(divius): implement
ip::Ipv6Addr(..) => panic!("IPv6 not implemented")
}
}
/// Get socket address from netbytes.
pub fn netaddr_from_netbytes(bytes: &[u8]) -> ip::SocketAddr {
assert_eq!(6, bytes.len());
ip::SocketAddr {
ip: ip::Ipv4Addr(bytes[0], bytes[1], bytes[2], bytes[3]),
port: ((bytes[4] as u16) << 8) + bytes[5] as u16
}
}
*/
| use num::traits::FromPrimitive;
use num;
use super::super::Node;
pub static ADDR: &'static str = "127.0.0.1:8008";
pub fn new_node(id: usize) -> Node {
new_node_with_port(id, 8008)
}
pub fn new_node_with_port(id: usize, port: u16) -> Node {
Node {
id: FromPrimitive::from_usize(id).unwrap(),
address: SocketAddr::V4( SocketAddrV4::new(
Ipv4Addr::new(127, 0, 0, 1),
port
) )
}
}
pub fn usize_to_id(id: usize) -> num::BigUint {
FromPrimitive::from_usize(id).unwrap()
}
} | #[cfg(test)]
pub mod test {
use std::net::SocketAddr;
use std::net::SocketAddrV4;
use std::net::Ipv4Addr; | random_line_split |
htmlbrelement.rs |
use dom::bindings::codegen::Bindings::HTMLBRElementBinding;
use dom::bindings::codegen::InheritTypes::HTMLBRElementDerived;
use dom::bindings::js::Root;
use dom::document::Document;
use dom::element::ElementTypeId;
use dom::eventtarget::{EventTarget, EventTargetTypeId};
use dom::htmlelement::{HTMLElement, HTMLElementTypeId};
use dom::node::{Node, NodeTypeId};
use util::str::DOMString;
#[dom_struct]
pub struct HTMLBRElement {
htmlelement: HTMLElement,
}
impl HTMLBRElementDerived for EventTarget {
fn is_htmlbrelement(&self) -> bool {
*self.type_id() ==
EventTargetTypeId::Node(
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLBRElement)))
}
}
impl HTMLBRElement {
fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: &Document) -> HTMLBRElement {
HTMLBRElement {
htmlelement: HTMLElement::new_inherited(HTMLElementTypeId::HTMLBRElement, localName, prefix, document)
}
}
#[allow(unrooted_must_root)]
pub fn new(localName: DOMString,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLBRElement> {
let element = HTMLBRElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLBRElementBinding::Wrap)
}
} | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ | random_line_split | |
htmlbrelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::HTMLBRElementBinding;
use dom::bindings::codegen::InheritTypes::HTMLBRElementDerived;
use dom::bindings::js::Root;
use dom::document::Document;
use dom::element::ElementTypeId;
use dom::eventtarget::{EventTarget, EventTargetTypeId};
use dom::htmlelement::{HTMLElement, HTMLElementTypeId};
use dom::node::{Node, NodeTypeId};
use util::str::DOMString;
#[dom_struct]
pub struct HTMLBRElement {
htmlelement: HTMLElement,
}
impl HTMLBRElementDerived for EventTarget {
fn is_htmlbrelement(&self) -> bool {
*self.type_id() ==
EventTargetTypeId::Node(
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLBRElement)))
}
}
impl HTMLBRElement {
fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: &Document) -> HTMLBRElement {
HTMLBRElement {
htmlelement: HTMLElement::new_inherited(HTMLElementTypeId::HTMLBRElement, localName, prefix, document)
}
}
#[allow(unrooted_must_root)]
pub fn new(localName: DOMString,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLBRElement> |
}
| {
let element = HTMLBRElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLBRElementBinding::Wrap)
} | identifier_body |
htmlbrelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::HTMLBRElementBinding;
use dom::bindings::codegen::InheritTypes::HTMLBRElementDerived;
use dom::bindings::js::Root;
use dom::document::Document;
use dom::element::ElementTypeId;
use dom::eventtarget::{EventTarget, EventTargetTypeId};
use dom::htmlelement::{HTMLElement, HTMLElementTypeId};
use dom::node::{Node, NodeTypeId};
use util::str::DOMString;
#[dom_struct]
pub struct | {
htmlelement: HTMLElement,
}
impl HTMLBRElementDerived for EventTarget {
fn is_htmlbrelement(&self) -> bool {
*self.type_id() ==
EventTargetTypeId::Node(
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLBRElement)))
}
}
impl HTMLBRElement {
fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: &Document) -> HTMLBRElement {
HTMLBRElement {
htmlelement: HTMLElement::new_inherited(HTMLElementTypeId::HTMLBRElement, localName, prefix, document)
}
}
#[allow(unrooted_must_root)]
pub fn new(localName: DOMString,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLBRElement> {
let element = HTMLBRElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLBRElementBinding::Wrap)
}
}
| HTMLBRElement | identifier_name |
issue-11709.rs | // 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.
// ignore-pretty
// Don't panic on blocks without results
// There are several tests in this run-pass that raised
// when this bug was opened. The cases where the compiler
// panics before the fix have a comment.
#![feature(std_misc)]
use std::thunk::Thunk;
struct S {x:()}
fn test(slot: &mut Option<Thunk<(),Thunk>>) -> () {
let a = slot.take();
let _a = match a {
// `{let.. a(); }` would break
Some(a) => { let _a = a(); },
None => (),
};
}
fn not(b: bool) -> bool {
if b {
!b
} else {
// `panic!(...)` would break
panic!("Break the compiler");
}
}
pub fn main() {
// {} would break
let _r = {};
let mut slot = None;
// `{ test(...); }` would break
let _s : S = S{ x: { test(&mut slot); } };
let _b = not(true);
} | random_line_split | |
issue-11709.rs | // 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.
// ignore-pretty
// Don't panic on blocks without results
// There are several tests in this run-pass that raised
// when this bug was opened. The cases where the compiler
// panics before the fix have a comment.
#![feature(std_misc)]
use std::thunk::Thunk;
struct | {x:()}
fn test(slot: &mut Option<Thunk<(),Thunk>>) -> () {
let a = slot.take();
let _a = match a {
// `{let.. a(); }` would break
Some(a) => { let _a = a(); },
None => (),
};
}
fn not(b: bool) -> bool {
if b {
!b
} else {
// `panic!(...)` would break
panic!("Break the compiler");
}
}
pub fn main() {
// {} would break
let _r = {};
let mut slot = None;
// `{ test(...); }` would break
let _s : S = S{ x: { test(&mut slot); } };
let _b = not(true);
}
| S | identifier_name |
rcdom.rs | // Copyright 2014 The html5ever Project Developers. See the
// COPYRIGHT file at the top-level directory of this distribution.
//
// 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.
//! A simple reference-counted DOM.
//!
//! This is sufficient as a static parse tree, but don't build a
//! web browser using it. :)
use std::ascii::AsciiExt;
use std::cell::RefCell;
use std::collections::HashSet;
use std::default::Default;
use std::borrow::Cow;
use std::io::{self, Write};
use std::mem;
use std::ops::{Deref, DerefMut};
use std::rc::{Rc, Weak};
use string_cache::QualName;
use tendril::StrTendril;
use tokenizer::Attribute;
use tree_builder::{TreeSink, QuirksMode, NodeOrText, AppendNode, AppendText};
use tree_builder;
use serialize::{Serializable, Serializer};
use serialize::TraversalScope;
use serialize::TraversalScope::{IncludeNode, ChildrenOnly};
pub use self::ElementEnum::{AnnotationXml, Normal, Script, Template};
pub use self::NodeEnum::{Document, Doctype, Text, Comment, Element};
/// The different kinds of elements in the DOM.
#[derive(Debug)]
pub enum ElementEnum {
Normal,
/// A script element and its "already started" flag.
/// https://html.spec.whatwg.org/multipage/#already-started
Script(bool),
/// A template element and its template contents.
/// https://html.spec.whatwg.org/multipage/#template-contents
Template(Handle),
/// An annotation-xml element in the MathML namespace whose start tag token had an attribute
/// with the name "encoding" whose value was an ASCII case-insensitive match for the string
/// "text/html" or "application/xhtml+xml"
/// https://html.spec.whatwg.org/multipage/embedded-content.html#math:annotation-xml
AnnotationXml(bool),
}
/// The different kinds of nodes in the DOM.
#[derive(Debug)]
pub enum NodeEnum {
/// The `Document` itself.
Document,
/// A `DOCTYPE` with name, public id, and system id.
Doctype(StrTendril, StrTendril, StrTendril),
/// A text node.
Text(StrTendril),
/// A comment.
Comment(StrTendril),
/// An element with attributes.
Element(QualName, ElementEnum, Vec<Attribute>),
}
/// A DOM node.
#[derive(Debug)]
pub struct Node {
pub node: NodeEnum,
pub parent: Option<WeakHandle>,
pub children: Vec<Handle>,
}
impl Node {
fn new(node: NodeEnum) -> Node {
Node {
node: node,
parent: None,
children: vec!(),
}
}
}
/// Reference to a DOM node.
#[derive(Clone, Debug)]
pub struct Handle(Rc<RefCell<Node>>);
impl Deref for Handle {
type Target = Rc<RefCell<Node>>;
fn deref(&self) -> &Rc<RefCell<Node>> { &self.0 }
}
/// Weak reference to a DOM node, used for parent pointers.
pub type WeakHandle = Weak<RefCell<Node>>;
#[allow(trivial_casts)]
fn same_node(x: &Handle, y: &Handle) -> bool {
// FIXME: This shouldn't really need to touch the borrow flags, right?
(&*x.borrow() as *const Node) == (&*y.borrow() as *const Node)
}
fn new_node(node: NodeEnum) -> Handle {
Handle(Rc::new(RefCell::new(Node::new(node))))
}
fn append(new_parent: &Handle, child: Handle) {
new_parent.borrow_mut().children.push(child.clone());
let parent = &mut child.borrow_mut().parent;
assert!(parent.is_none());
*parent = Some(Rc::downgrade(new_parent));
}
fn get_parent_and_index(target: &Handle) -> Option<(Handle, usize)> {
let child = target.borrow();
let parent = unwrap_or_return!(child.parent.as_ref(), None)
.upgrade().expect("dangling weak pointer");
let i = match parent.borrow_mut().children.iter().enumerate()
.find(|&(_, n)| same_node(n, target)) {
Some((i, _)) => i,
None => panic!("have parent but couldn't find in parent's children!"),
};
Some((Handle(parent), i))
}
fn append_to_existing_text(prev: &Handle, text: &str) -> bool {
match prev.borrow_mut().deref_mut().node {
Text(ref mut existing) => {
existing.push_slice(text);
true
}
_ => false,
}
}
fn remove_from_parent(target: &Handle) {
{
let (parent, i) = unwrap_or_return!(get_parent_and_index(target), ());
parent.borrow_mut().children.remove(i);
}
let mut child = target.borrow_mut();
(*child).parent = None;
}
/// The DOM itself; the result of parsing.
pub struct RcDom {
/// The `Document` itself.
pub document: Handle,
/// Errors that occurred during parsing.
pub errors: Vec<Cow<'static, str>>,
/// The document's quirks mode.
pub quirks_mode: QuirksMode,
}
impl TreeSink for RcDom {
type Output = Self;
fn finish(self) -> Self { self }
type Handle = Handle;
fn parse_error(&mut self, msg: Cow<'static, str>) {
self.errors.push(msg);
}
fn get_document(&mut self) -> Handle {
self.document.clone()
}
fn get_template_contents(&mut self, target: Handle) -> Handle {
if let Element(_, Template(ref contents), _) = target.borrow().node {
contents.clone()
} else {
panic!("not a template element!")
}
}
fn set_quirks_mode(&mut self, mode: QuirksMode) {
self.quirks_mode = mode;
}
fn same_node(&self, x: Handle, y: Handle) -> bool {
same_node(&x, &y)
}
fn elem_name(&self, target: Handle) -> QualName {
// FIXME: rust-lang/rust#22252
if let Element(ref name, _, _) = target.borrow().node {
name.clone()
} else {
panic!("not an element!")
}
}
fn create_element(&mut self, name: QualName, attrs: Vec<Attribute>) -> Handle {
let info = match name {
qualname!(html, "script") => Script(false),
qualname!(html, "template") => Template(new_node(Document)),
qualname!(mathml, "annotation-xml") => {
AnnotationXml(attrs.iter().find(|attr| attr.name == qualname!("", "encoding"))
.map_or(false,
|attr| attr.value
.eq_ignore_ascii_case("text/html") ||
attr.value
.eq_ignore_ascii_case("application/xhtml+xml")))
},
_ => Normal,
};
new_node(Element(name, info, attrs))
}
fn create_comment(&mut self, text: StrTendril) -> Handle {
new_node(Comment(text))
}
fn append(&mut self, parent: Handle, child: NodeOrText<Handle>) {
// Append to an existing Text node if we have one.
match child {
AppendText(ref text) => match parent.borrow().children.last() {
Some(h) => if append_to_existing_text(h, &text) { return; },
_ => (),
},
_ => (),
}
append(&parent, match child {
AppendText(text) => new_node(Text(text)),
AppendNode(node) => node
});
}
fn append_before_sibling(&mut self,
sibling: Handle,
child: NodeOrText<Handle>) -> Result<(), NodeOrText<Handle>> {
let (parent, i) = unwrap_or_return!(get_parent_and_index(&sibling), Err(child));
let child = match (child, i) {
// No previous node.
(AppendText(text), 0) => new_node(Text(text)),
// Look for a text node before the insertion point.
(AppendText(text), i) => {
let parent = parent.borrow();
let prev = &parent.children[i-1];
if append_to_existing_text(prev, &text) {
return Ok(());
}
new_node(Text(text))
}
// The tree builder promises we won't have a text node after
// the insertion point.
// Any other kind of node.
(AppendNode(node), _) => node,
};
if child.borrow().parent.is_some() {
remove_from_parent(&child);
}
child.borrow_mut().parent = Some(Rc::downgrade(&parent));
parent.borrow_mut().children.insert(i, child);
Ok(())
}
fn append_doctype_to_document(&mut self,
name: StrTendril,
public_id: StrTendril,
system_id: StrTendril) {
append(&self.document, new_node(Doctype(name, public_id, system_id)));
}
fn add_attrs_if_missing(&mut self, target: Handle, attrs: Vec<Attribute>) {
let mut node = target.borrow_mut();
let existing = if let Element(_, _, ref mut attrs) = node.deref_mut().node {
attrs
} else {
panic!("not an element")
};
let existing_names =
existing.iter().map(|e| e.name.clone()).collect::<HashSet<_>>();
existing.extend(attrs.into_iter().filter(|attr| {
!existing_names.contains(&attr.name)
}));
}
fn remove_from_parent(&mut self, target: Handle) {
remove_from_parent(&target);
}
fn reparent_children(&mut self, node: Handle, new_parent: Handle) {
let children = &mut node.borrow_mut().children;
let new_children = &mut new_parent.borrow_mut().children;
for child in children.iter() {
// FIXME: It would be nice to assert that the child's parent is node, but I haven't
// found a way to do that that doesn't create overlapping borrows of RefCells.
let parent = &mut child.borrow_mut().parent;
*parent = Some(Rc::downgrade(&new_parent));
}
new_children.extend(mem::replace(children, Vec::new()).into_iter());
}
fn mark_script_already_started(&mut self, target: Handle) {
if let Element(_, Script(ref mut script_already_started), _) = target.borrow_mut().node {
*script_already_started = true;
} else {
panic!("not a script element!");
}
}
fn is_mathml_annotation_xml_integration_point(&self, handle: Self::Handle) -> bool {
match (**handle).borrow().node {
Element(_, AnnotationXml(ret), _) => ret,
_ => unreachable!(),
}
}
}
impl Default for RcDom {
fn default() -> RcDom {
RcDom {
document: new_node(Document),
errors: vec!(),
quirks_mode: tree_builder::NoQuirks,
}
}
}
impl Serializable for Handle {
fn serialize<'wr, Wr: Write>(&self, serializer: &mut Serializer<'wr, Wr>,
traversal_scope: TraversalScope) -> io::Result<()> | for handle in node.children.iter() {
try!(handle.clone().serialize(serializer, IncludeNode));
}
Ok(())
}
(ChildrenOnly, _) => Ok(()),
(IncludeNode, &Doctype(ref name, _, _)) => serializer.write_doctype(&name),
(IncludeNode, &Text(ref text)) => serializer.write_text(&text),
(IncludeNode, &Comment(ref text)) => serializer.write_comment(&text),
(IncludeNode, &Document) => panic!("Can't serialize Document node itself"),
}
}
}
| {
let node = self.borrow();
match (traversal_scope, &node.node) {
(_, &Element(ref name, _, ref attrs)) => {
if traversal_scope == IncludeNode {
try!(serializer.start_elem(name.clone(),
attrs.iter().map(|at| (&at.name, &at.value[..]))));
}
for handle in node.children.iter() {
try!(handle.clone().serialize(serializer, IncludeNode));
}
if traversal_scope == IncludeNode {
try!(serializer.end_elem(name.clone()));
}
Ok(())
}
(ChildrenOnly, &Document) => { | identifier_body |
rcdom.rs | // Copyright 2014 The html5ever Project Developers. See the
// COPYRIGHT file at the top-level directory of this distribution.
//
// 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.
//! A simple reference-counted DOM.
//!
//! This is sufficient as a static parse tree, but don't build a
//! web browser using it. :)
use std::ascii::AsciiExt;
use std::cell::RefCell;
use std::collections::HashSet;
use std::default::Default;
use std::borrow::Cow;
use std::io::{self, Write};
use std::mem;
use std::ops::{Deref, DerefMut};
use std::rc::{Rc, Weak};
use string_cache::QualName;
use tendril::StrTendril;
use tokenizer::Attribute;
use tree_builder::{TreeSink, QuirksMode, NodeOrText, AppendNode, AppendText};
use tree_builder;
use serialize::{Serializable, Serializer};
use serialize::TraversalScope;
use serialize::TraversalScope::{IncludeNode, ChildrenOnly};
pub use self::ElementEnum::{AnnotationXml, Normal, Script, Template};
pub use self::NodeEnum::{Document, Doctype, Text, Comment, Element};
/// The different kinds of elements in the DOM.
#[derive(Debug)]
pub enum ElementEnum {
Normal,
/// A script element and its "already started" flag.
/// https://html.spec.whatwg.org/multipage/#already-started
Script(bool),
/// A template element and its template contents.
/// https://html.spec.whatwg.org/multipage/#template-contents
Template(Handle),
/// An annotation-xml element in the MathML namespace whose start tag token had an attribute
/// with the name "encoding" whose value was an ASCII case-insensitive match for the string
/// "text/html" or "application/xhtml+xml"
/// https://html.spec.whatwg.org/multipage/embedded-content.html#math:annotation-xml
AnnotationXml(bool),
}
/// The different kinds of nodes in the DOM.
#[derive(Debug)]
pub enum NodeEnum {
/// The `Document` itself.
Document,
/// A `DOCTYPE` with name, public id, and system id.
Doctype(StrTendril, StrTendril, StrTendril),
/// A text node.
Text(StrTendril),
/// A comment.
Comment(StrTendril),
/// An element with attributes.
Element(QualName, ElementEnum, Vec<Attribute>),
}
/// A DOM node. | pub children: Vec<Handle>,
}
impl Node {
fn new(node: NodeEnum) -> Node {
Node {
node: node,
parent: None,
children: vec!(),
}
}
}
/// Reference to a DOM node.
#[derive(Clone, Debug)]
pub struct Handle(Rc<RefCell<Node>>);
impl Deref for Handle {
type Target = Rc<RefCell<Node>>;
fn deref(&self) -> &Rc<RefCell<Node>> { &self.0 }
}
/// Weak reference to a DOM node, used for parent pointers.
pub type WeakHandle = Weak<RefCell<Node>>;
#[allow(trivial_casts)]
fn same_node(x: &Handle, y: &Handle) -> bool {
// FIXME: This shouldn't really need to touch the borrow flags, right?
(&*x.borrow() as *const Node) == (&*y.borrow() as *const Node)
}
fn new_node(node: NodeEnum) -> Handle {
Handle(Rc::new(RefCell::new(Node::new(node))))
}
fn append(new_parent: &Handle, child: Handle) {
new_parent.borrow_mut().children.push(child.clone());
let parent = &mut child.borrow_mut().parent;
assert!(parent.is_none());
*parent = Some(Rc::downgrade(new_parent));
}
fn get_parent_and_index(target: &Handle) -> Option<(Handle, usize)> {
let child = target.borrow();
let parent = unwrap_or_return!(child.parent.as_ref(), None)
.upgrade().expect("dangling weak pointer");
let i = match parent.borrow_mut().children.iter().enumerate()
.find(|&(_, n)| same_node(n, target)) {
Some((i, _)) => i,
None => panic!("have parent but couldn't find in parent's children!"),
};
Some((Handle(parent), i))
}
fn append_to_existing_text(prev: &Handle, text: &str) -> bool {
match prev.borrow_mut().deref_mut().node {
Text(ref mut existing) => {
existing.push_slice(text);
true
}
_ => false,
}
}
fn remove_from_parent(target: &Handle) {
{
let (parent, i) = unwrap_or_return!(get_parent_and_index(target), ());
parent.borrow_mut().children.remove(i);
}
let mut child = target.borrow_mut();
(*child).parent = None;
}
/// The DOM itself; the result of parsing.
pub struct RcDom {
/// The `Document` itself.
pub document: Handle,
/// Errors that occurred during parsing.
pub errors: Vec<Cow<'static, str>>,
/// The document's quirks mode.
pub quirks_mode: QuirksMode,
}
impl TreeSink for RcDom {
type Output = Self;
fn finish(self) -> Self { self }
type Handle = Handle;
fn parse_error(&mut self, msg: Cow<'static, str>) {
self.errors.push(msg);
}
fn get_document(&mut self) -> Handle {
self.document.clone()
}
fn get_template_contents(&mut self, target: Handle) -> Handle {
if let Element(_, Template(ref contents), _) = target.borrow().node {
contents.clone()
} else {
panic!("not a template element!")
}
}
fn set_quirks_mode(&mut self, mode: QuirksMode) {
self.quirks_mode = mode;
}
fn same_node(&self, x: Handle, y: Handle) -> bool {
same_node(&x, &y)
}
fn elem_name(&self, target: Handle) -> QualName {
// FIXME: rust-lang/rust#22252
if let Element(ref name, _, _) = target.borrow().node {
name.clone()
} else {
panic!("not an element!")
}
}
fn create_element(&mut self, name: QualName, attrs: Vec<Attribute>) -> Handle {
let info = match name {
qualname!(html, "script") => Script(false),
qualname!(html, "template") => Template(new_node(Document)),
qualname!(mathml, "annotation-xml") => {
AnnotationXml(attrs.iter().find(|attr| attr.name == qualname!("", "encoding"))
.map_or(false,
|attr| attr.value
.eq_ignore_ascii_case("text/html") ||
attr.value
.eq_ignore_ascii_case("application/xhtml+xml")))
},
_ => Normal,
};
new_node(Element(name, info, attrs))
}
fn create_comment(&mut self, text: StrTendril) -> Handle {
new_node(Comment(text))
}
fn append(&mut self, parent: Handle, child: NodeOrText<Handle>) {
// Append to an existing Text node if we have one.
match child {
AppendText(ref text) => match parent.borrow().children.last() {
Some(h) => if append_to_existing_text(h, &text) { return; },
_ => (),
},
_ => (),
}
append(&parent, match child {
AppendText(text) => new_node(Text(text)),
AppendNode(node) => node
});
}
fn append_before_sibling(&mut self,
sibling: Handle,
child: NodeOrText<Handle>) -> Result<(), NodeOrText<Handle>> {
let (parent, i) = unwrap_or_return!(get_parent_and_index(&sibling), Err(child));
let child = match (child, i) {
// No previous node.
(AppendText(text), 0) => new_node(Text(text)),
// Look for a text node before the insertion point.
(AppendText(text), i) => {
let parent = parent.borrow();
let prev = &parent.children[i-1];
if append_to_existing_text(prev, &text) {
return Ok(());
}
new_node(Text(text))
}
// The tree builder promises we won't have a text node after
// the insertion point.
// Any other kind of node.
(AppendNode(node), _) => node,
};
if child.borrow().parent.is_some() {
remove_from_parent(&child);
}
child.borrow_mut().parent = Some(Rc::downgrade(&parent));
parent.borrow_mut().children.insert(i, child);
Ok(())
}
fn append_doctype_to_document(&mut self,
name: StrTendril,
public_id: StrTendril,
system_id: StrTendril) {
append(&self.document, new_node(Doctype(name, public_id, system_id)));
}
fn add_attrs_if_missing(&mut self, target: Handle, attrs: Vec<Attribute>) {
let mut node = target.borrow_mut();
let existing = if let Element(_, _, ref mut attrs) = node.deref_mut().node {
attrs
} else {
panic!("not an element")
};
let existing_names =
existing.iter().map(|e| e.name.clone()).collect::<HashSet<_>>();
existing.extend(attrs.into_iter().filter(|attr| {
!existing_names.contains(&attr.name)
}));
}
fn remove_from_parent(&mut self, target: Handle) {
remove_from_parent(&target);
}
fn reparent_children(&mut self, node: Handle, new_parent: Handle) {
let children = &mut node.borrow_mut().children;
let new_children = &mut new_parent.borrow_mut().children;
for child in children.iter() {
// FIXME: It would be nice to assert that the child's parent is node, but I haven't
// found a way to do that that doesn't create overlapping borrows of RefCells.
let parent = &mut child.borrow_mut().parent;
*parent = Some(Rc::downgrade(&new_parent));
}
new_children.extend(mem::replace(children, Vec::new()).into_iter());
}
fn mark_script_already_started(&mut self, target: Handle) {
if let Element(_, Script(ref mut script_already_started), _) = target.borrow_mut().node {
*script_already_started = true;
} else {
panic!("not a script element!");
}
}
fn is_mathml_annotation_xml_integration_point(&self, handle: Self::Handle) -> bool {
match (**handle).borrow().node {
Element(_, AnnotationXml(ret), _) => ret,
_ => unreachable!(),
}
}
}
impl Default for RcDom {
fn default() -> RcDom {
RcDom {
document: new_node(Document),
errors: vec!(),
quirks_mode: tree_builder::NoQuirks,
}
}
}
impl Serializable for Handle {
fn serialize<'wr, Wr: Write>(&self, serializer: &mut Serializer<'wr, Wr>,
traversal_scope: TraversalScope) -> io::Result<()> {
let node = self.borrow();
match (traversal_scope, &node.node) {
(_, &Element(ref name, _, ref attrs)) => {
if traversal_scope == IncludeNode {
try!(serializer.start_elem(name.clone(),
attrs.iter().map(|at| (&at.name, &at.value[..]))));
}
for handle in node.children.iter() {
try!(handle.clone().serialize(serializer, IncludeNode));
}
if traversal_scope == IncludeNode {
try!(serializer.end_elem(name.clone()));
}
Ok(())
}
(ChildrenOnly, &Document) => {
for handle in node.children.iter() {
try!(handle.clone().serialize(serializer, IncludeNode));
}
Ok(())
}
(ChildrenOnly, _) => Ok(()),
(IncludeNode, &Doctype(ref name, _, _)) => serializer.write_doctype(&name),
(IncludeNode, &Text(ref text)) => serializer.write_text(&text),
(IncludeNode, &Comment(ref text)) => serializer.write_comment(&text),
(IncludeNode, &Document) => panic!("Can't serialize Document node itself"),
}
}
} | #[derive(Debug)]
pub struct Node {
pub node: NodeEnum,
pub parent: Option<WeakHandle>, | random_line_split |
rcdom.rs | // Copyright 2014 The html5ever Project Developers. See the
// COPYRIGHT file at the top-level directory of this distribution.
//
// 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.
//! A simple reference-counted DOM.
//!
//! This is sufficient as a static parse tree, but don't build a
//! web browser using it. :)
use std::ascii::AsciiExt;
use std::cell::RefCell;
use std::collections::HashSet;
use std::default::Default;
use std::borrow::Cow;
use std::io::{self, Write};
use std::mem;
use std::ops::{Deref, DerefMut};
use std::rc::{Rc, Weak};
use string_cache::QualName;
use tendril::StrTendril;
use tokenizer::Attribute;
use tree_builder::{TreeSink, QuirksMode, NodeOrText, AppendNode, AppendText};
use tree_builder;
use serialize::{Serializable, Serializer};
use serialize::TraversalScope;
use serialize::TraversalScope::{IncludeNode, ChildrenOnly};
pub use self::ElementEnum::{AnnotationXml, Normal, Script, Template};
pub use self::NodeEnum::{Document, Doctype, Text, Comment, Element};
/// The different kinds of elements in the DOM.
#[derive(Debug)]
pub enum ElementEnum {
Normal,
/// A script element and its "already started" flag.
/// https://html.spec.whatwg.org/multipage/#already-started
Script(bool),
/// A template element and its template contents.
/// https://html.spec.whatwg.org/multipage/#template-contents
Template(Handle),
/// An annotation-xml element in the MathML namespace whose start tag token had an attribute
/// with the name "encoding" whose value was an ASCII case-insensitive match for the string
/// "text/html" or "application/xhtml+xml"
/// https://html.spec.whatwg.org/multipage/embedded-content.html#math:annotation-xml
AnnotationXml(bool),
}
/// The different kinds of nodes in the DOM.
#[derive(Debug)]
pub enum NodeEnum {
/// The `Document` itself.
Document,
/// A `DOCTYPE` with name, public id, and system id.
Doctype(StrTendril, StrTendril, StrTendril),
/// A text node.
Text(StrTendril),
/// A comment.
Comment(StrTendril),
/// An element with attributes.
Element(QualName, ElementEnum, Vec<Attribute>),
}
/// A DOM node.
#[derive(Debug)]
pub struct Node {
pub node: NodeEnum,
pub parent: Option<WeakHandle>,
pub children: Vec<Handle>,
}
impl Node {
fn new(node: NodeEnum) -> Node {
Node {
node: node,
parent: None,
children: vec!(),
}
}
}
/// Reference to a DOM node.
#[derive(Clone, Debug)]
pub struct | (Rc<RefCell<Node>>);
impl Deref for Handle {
type Target = Rc<RefCell<Node>>;
fn deref(&self) -> &Rc<RefCell<Node>> { &self.0 }
}
/// Weak reference to a DOM node, used for parent pointers.
pub type WeakHandle = Weak<RefCell<Node>>;
#[allow(trivial_casts)]
fn same_node(x: &Handle, y: &Handle) -> bool {
// FIXME: This shouldn't really need to touch the borrow flags, right?
(&*x.borrow() as *const Node) == (&*y.borrow() as *const Node)
}
fn new_node(node: NodeEnum) -> Handle {
Handle(Rc::new(RefCell::new(Node::new(node))))
}
fn append(new_parent: &Handle, child: Handle) {
new_parent.borrow_mut().children.push(child.clone());
let parent = &mut child.borrow_mut().parent;
assert!(parent.is_none());
*parent = Some(Rc::downgrade(new_parent));
}
fn get_parent_and_index(target: &Handle) -> Option<(Handle, usize)> {
let child = target.borrow();
let parent = unwrap_or_return!(child.parent.as_ref(), None)
.upgrade().expect("dangling weak pointer");
let i = match parent.borrow_mut().children.iter().enumerate()
.find(|&(_, n)| same_node(n, target)) {
Some((i, _)) => i,
None => panic!("have parent but couldn't find in parent's children!"),
};
Some((Handle(parent), i))
}
fn append_to_existing_text(prev: &Handle, text: &str) -> bool {
match prev.borrow_mut().deref_mut().node {
Text(ref mut existing) => {
existing.push_slice(text);
true
}
_ => false,
}
}
fn remove_from_parent(target: &Handle) {
{
let (parent, i) = unwrap_or_return!(get_parent_and_index(target), ());
parent.borrow_mut().children.remove(i);
}
let mut child = target.borrow_mut();
(*child).parent = None;
}
/// The DOM itself; the result of parsing.
pub struct RcDom {
/// The `Document` itself.
pub document: Handle,
/// Errors that occurred during parsing.
pub errors: Vec<Cow<'static, str>>,
/// The document's quirks mode.
pub quirks_mode: QuirksMode,
}
impl TreeSink for RcDom {
type Output = Self;
fn finish(self) -> Self { self }
type Handle = Handle;
fn parse_error(&mut self, msg: Cow<'static, str>) {
self.errors.push(msg);
}
fn get_document(&mut self) -> Handle {
self.document.clone()
}
fn get_template_contents(&mut self, target: Handle) -> Handle {
if let Element(_, Template(ref contents), _) = target.borrow().node {
contents.clone()
} else {
panic!("not a template element!")
}
}
fn set_quirks_mode(&mut self, mode: QuirksMode) {
self.quirks_mode = mode;
}
fn same_node(&self, x: Handle, y: Handle) -> bool {
same_node(&x, &y)
}
fn elem_name(&self, target: Handle) -> QualName {
// FIXME: rust-lang/rust#22252
if let Element(ref name, _, _) = target.borrow().node {
name.clone()
} else {
panic!("not an element!")
}
}
fn create_element(&mut self, name: QualName, attrs: Vec<Attribute>) -> Handle {
let info = match name {
qualname!(html, "script") => Script(false),
qualname!(html, "template") => Template(new_node(Document)),
qualname!(mathml, "annotation-xml") => {
AnnotationXml(attrs.iter().find(|attr| attr.name == qualname!("", "encoding"))
.map_or(false,
|attr| attr.value
.eq_ignore_ascii_case("text/html") ||
attr.value
.eq_ignore_ascii_case("application/xhtml+xml")))
},
_ => Normal,
};
new_node(Element(name, info, attrs))
}
fn create_comment(&mut self, text: StrTendril) -> Handle {
new_node(Comment(text))
}
fn append(&mut self, parent: Handle, child: NodeOrText<Handle>) {
// Append to an existing Text node if we have one.
match child {
AppendText(ref text) => match parent.borrow().children.last() {
Some(h) => if append_to_existing_text(h, &text) { return; },
_ => (),
},
_ => (),
}
append(&parent, match child {
AppendText(text) => new_node(Text(text)),
AppendNode(node) => node
});
}
fn append_before_sibling(&mut self,
sibling: Handle,
child: NodeOrText<Handle>) -> Result<(), NodeOrText<Handle>> {
let (parent, i) = unwrap_or_return!(get_parent_and_index(&sibling), Err(child));
let child = match (child, i) {
// No previous node.
(AppendText(text), 0) => new_node(Text(text)),
// Look for a text node before the insertion point.
(AppendText(text), i) => {
let parent = parent.borrow();
let prev = &parent.children[i-1];
if append_to_existing_text(prev, &text) {
return Ok(());
}
new_node(Text(text))
}
// The tree builder promises we won't have a text node after
// the insertion point.
// Any other kind of node.
(AppendNode(node), _) => node,
};
if child.borrow().parent.is_some() {
remove_from_parent(&child);
}
child.borrow_mut().parent = Some(Rc::downgrade(&parent));
parent.borrow_mut().children.insert(i, child);
Ok(())
}
fn append_doctype_to_document(&mut self,
name: StrTendril,
public_id: StrTendril,
system_id: StrTendril) {
append(&self.document, new_node(Doctype(name, public_id, system_id)));
}
fn add_attrs_if_missing(&mut self, target: Handle, attrs: Vec<Attribute>) {
let mut node = target.borrow_mut();
let existing = if let Element(_, _, ref mut attrs) = node.deref_mut().node {
attrs
} else {
panic!("not an element")
};
let existing_names =
existing.iter().map(|e| e.name.clone()).collect::<HashSet<_>>();
existing.extend(attrs.into_iter().filter(|attr| {
!existing_names.contains(&attr.name)
}));
}
fn remove_from_parent(&mut self, target: Handle) {
remove_from_parent(&target);
}
fn reparent_children(&mut self, node: Handle, new_parent: Handle) {
let children = &mut node.borrow_mut().children;
let new_children = &mut new_parent.borrow_mut().children;
for child in children.iter() {
// FIXME: It would be nice to assert that the child's parent is node, but I haven't
// found a way to do that that doesn't create overlapping borrows of RefCells.
let parent = &mut child.borrow_mut().parent;
*parent = Some(Rc::downgrade(&new_parent));
}
new_children.extend(mem::replace(children, Vec::new()).into_iter());
}
fn mark_script_already_started(&mut self, target: Handle) {
if let Element(_, Script(ref mut script_already_started), _) = target.borrow_mut().node {
*script_already_started = true;
} else {
panic!("not a script element!");
}
}
fn is_mathml_annotation_xml_integration_point(&self, handle: Self::Handle) -> bool {
match (**handle).borrow().node {
Element(_, AnnotationXml(ret), _) => ret,
_ => unreachable!(),
}
}
}
impl Default for RcDom {
fn default() -> RcDom {
RcDom {
document: new_node(Document),
errors: vec!(),
quirks_mode: tree_builder::NoQuirks,
}
}
}
impl Serializable for Handle {
fn serialize<'wr, Wr: Write>(&self, serializer: &mut Serializer<'wr, Wr>,
traversal_scope: TraversalScope) -> io::Result<()> {
let node = self.borrow();
match (traversal_scope, &node.node) {
(_, &Element(ref name, _, ref attrs)) => {
if traversal_scope == IncludeNode {
try!(serializer.start_elem(name.clone(),
attrs.iter().map(|at| (&at.name, &at.value[..]))));
}
for handle in node.children.iter() {
try!(handle.clone().serialize(serializer, IncludeNode));
}
if traversal_scope == IncludeNode {
try!(serializer.end_elem(name.clone()));
}
Ok(())
}
(ChildrenOnly, &Document) => {
for handle in node.children.iter() {
try!(handle.clone().serialize(serializer, IncludeNode));
}
Ok(())
}
(ChildrenOnly, _) => Ok(()),
(IncludeNode, &Doctype(ref name, _, _)) => serializer.write_doctype(&name),
(IncludeNode, &Text(ref text)) => serializer.write_text(&text),
(IncludeNode, &Comment(ref text)) => serializer.write_comment(&text),
(IncludeNode, &Document) => panic!("Can't serialize Document node itself"),
}
}
}
| Handle | identifier_name |
main.rs | extern crate time;
use time::Duration;
fn main() {
let duration = Duration::span(|| {
let n: i32 = 10000000;
let mut h: Vec<i32> = (0..n).collect();
make_heap(&mut *h);
for i in (1..n as usize).rev() {
h.swap(0, i);
push_down(0, i, &mut *h);
}
for (elt, i) in h.iter().zip(0..n) {
assert!(*elt == i);
}
});
println!("Done in {}", duration.num_milliseconds());
}
fn make_heap(h: &mut [i32]) {
for i in (0..h.len() / 2).rev() {
push_down(i, h.len(), h);
}
}
fn push_down(mut pos: usize, size: usize, h: &mut [i32]) {
while 2 * pos + 1 < size {
let mut vic = 2 * pos + 1;
if vic + 1 < size && h[vic + 1] > h[vic] |
if h[pos] > h[vic] {
break;
}
h.swap(pos, vic);
pos = vic;
}
}
| {
vic += 1;
} | conditional_block |
main.rs | extern crate time;
use time::Duration;
fn main() {
let duration = Duration::span(|| {
let n: i32 = 10000000;
let mut h: Vec<i32> = (0..n).collect();
make_heap(&mut *h);
for i in (1..n as usize).rev() {
h.swap(0, i);
push_down(0, i, &mut *h);
}
for (elt, i) in h.iter().zip(0..n) {
assert!(*elt == i);
}
});
println!("Done in {}", duration.num_milliseconds()); | }
fn make_heap(h: &mut [i32]) {
for i in (0..h.len() / 2).rev() {
push_down(i, h.len(), h);
}
}
fn push_down(mut pos: usize, size: usize, h: &mut [i32]) {
while 2 * pos + 1 < size {
let mut vic = 2 * pos + 1;
if vic + 1 < size && h[vic + 1] > h[vic] {
vic += 1;
}
if h[pos] > h[vic] {
break;
}
h.swap(pos, vic);
pos = vic;
}
} | random_line_split | |
main.rs | extern crate time;
use time::Duration;
fn main() {
let duration = Duration::span(|| {
let n: i32 = 10000000;
let mut h: Vec<i32> = (0..n).collect();
make_heap(&mut *h);
for i in (1..n as usize).rev() {
h.swap(0, i);
push_down(0, i, &mut *h);
}
for (elt, i) in h.iter().zip(0..n) {
assert!(*elt == i);
}
});
println!("Done in {}", duration.num_milliseconds());
}
fn make_heap(h: &mut [i32]) |
fn push_down(mut pos: usize, size: usize, h: &mut [i32]) {
while 2 * pos + 1 < size {
let mut vic = 2 * pos + 1;
if vic + 1 < size && h[vic + 1] > h[vic] {
vic += 1;
}
if h[pos] > h[vic] {
break;
}
h.swap(pos, vic);
pos = vic;
}
}
| {
for i in (0..h.len() / 2).rev() {
push_down(i, h.len(), h);
}
} | identifier_body |
main.rs | extern crate time;
use time::Duration;
fn main() {
let duration = Duration::span(|| {
let n: i32 = 10000000;
let mut h: Vec<i32> = (0..n).collect();
make_heap(&mut *h);
for i in (1..n as usize).rev() {
h.swap(0, i);
push_down(0, i, &mut *h);
}
for (elt, i) in h.iter().zip(0..n) {
assert!(*elt == i);
}
});
println!("Done in {}", duration.num_milliseconds());
}
fn | (h: &mut [i32]) {
for i in (0..h.len() / 2).rev() {
push_down(i, h.len(), h);
}
}
fn push_down(mut pos: usize, size: usize, h: &mut [i32]) {
while 2 * pos + 1 < size {
let mut vic = 2 * pos + 1;
if vic + 1 < size && h[vic + 1] > h[vic] {
vic += 1;
}
if h[pos] > h[vic] {
break;
}
h.swap(pos, vic);
pos = vic;
}
}
| make_heap | identifier_name |
issue-5688.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
/*
# Corrupted initialization in the static struct
...should print &[1, 2, 3] but instead prints something like
&[4492532864, 24]. It is pretty evident that the compiler messed up
with the representation of [int,..n] and [int] somehow, or at least
failed to typecheck correctly.
*/
struct X { vec: &'static [int] }
static V: &'static [X] = &[X { vec: &[1, 2, 3] }];
pub fn main() | {
for &v in V.iter() {
println!("{}", v.vec);
}
} | identifier_body | |
issue-5688.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
/*
# Corrupted initialization in the static struct
...should print &[1, 2, 3] but instead prints something like
&[4492532864, 24]. It is pretty evident that the compiler messed up
with the representation of [int,..n] and [int] somehow, or at least
failed to typecheck correctly.
*/ | for &v in V.iter() {
println!("{}", v.vec);
}
} |
struct X { vec: &'static [int] }
static V: &'static [X] = &[X { vec: &[1, 2, 3] }];
pub fn main() { | random_line_split |
issue-5688.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
/*
# Corrupted initialization in the static struct
...should print &[1, 2, 3] but instead prints something like
&[4492532864, 24]. It is pretty evident that the compiler messed up
with the representation of [int,..n] and [int] somehow, or at least
failed to typecheck correctly.
*/
struct X { vec: &'static [int] }
static V: &'static [X] = &[X { vec: &[1, 2, 3] }];
pub fn | () {
for &v in V.iter() {
println!("{}", v.vec);
}
}
| main | identifier_name |
buffer.rs | use std::iter::FromIterator;
use std::io::{
BufRead,
Write
};
use std::vec::IntoIter;
use std::ops;
use Result;
#[derive(Debug)]
pub struct Buffer {
lines: Vec<String>,
cached_num_lines: usize,
modified: bool
}
trait InsertAll {
type Item;
fn insert_all<I: IntoIterator<Item=Self::Item>>(&mut self, pos: usize, insert: I) -> usize;
}
impl <T> InsertAll for Vec<T> {
type Item = T;
fn insert_all<I: IntoIterator<Item=Self::Item>>(&mut self, pos: usize, insert: I) -> usize {
let mut count = 0 as usize;
for (index, item) in insert.into_iter().enumerate() {
self.insert( pos + index, item );
count += 1;
}
count
}
}
impl FromIterator<String> for Buffer {
fn from_iter<T>(iter: T) -> Buffer
where T: IntoIterator<Item=String> {
let mut buffer = Buffer::new();
buffer.insert_lines(0, iter);
return buffer
}
}
impl IntoIterator for Buffer {
type Item = String;
type IntoIter = IntoIter<String>;
fn into_iter(self) -> Self::IntoIter {
self.lines.into_iter()
}
}
impl Buffer {
pub fn new() -> Buffer {
Buffer {
lines: Vec::new(),
cached_num_lines: 0 as usize,
modified: false
}
}
pub fn from_buf_read<R: BufRead + Sized> (buf_read: R) -> Result<Buffer> {
let lines = buf_read.lines();
let lines_vec = lines.map(|r| r.unwrap()).collect::<Vec<String>>();
let cached_len = lines_vec.len();
Ok(Buffer {
lines: lines_vec,
cached_num_lines: cached_len,
modified: false
})
}
pub fn insert_lines<I: IntoIterator<Item=String>>(&mut self, pos: usize, insert: I) {
let added_lines = self.lines.insert_all(pos, insert);
self.cached_num_lines += added_lines;
self.modified = true;
}
pub fn insert_buffer(&mut self, pos: usize, buffer: Buffer) {
self.lines.insert_all(pos, buffer.lines);
self.cached_num_lines += buffer.cached_num_lines;
self.modified = true;
}
pub fn add_line(&mut self, line: String) {
self.lines.push(line);
self.cached_num_lines += 1;
self.modified = true;
}
pub fn delete_lines(&mut self, start: usize, end: usize) {
for _ in start..end {
self.lines.remove(start);
}
self.cached_num_lines -= end - start;
}
pub fn is_empty(&self) -> bool {
self.cached_num_lines == 0
}
pub fn has_changes(&self) -> bool {
self.modified
}
pub fn len(&self) -> usize {
self.cached_num_lines
}
pub fn is_out_of_bounds(&self, pos: usize) -> bool {
pos > self.len() | self.is_out_of_bounds(range.start) || self.is_out_of_bounds(range.end)
}
pub fn get_lines(&self, range: &ops::Range<usize>) -> &[String] {
assert!(! self.is_out_of_bounds( range.start ), format!("Out of bounds: {}/0", range.start) );
assert!(! self.is_out_of_bounds( range.end ), format!("Out of bounds: {}/{}", range.end, self.len()) );
&self.lines[ range.start.. range.end ]
}
pub fn write<W: Write>(&self, w:&mut W) -> Result<()> {
for line in self.lines.iter() {
try!( w.write_all( line.as_bytes() ) );
}
Ok(())
}
} | }
pub fn is_range_out_of_bounds(&self, range: &ops::Range<usize>) -> bool { | random_line_split |
buffer.rs |
use std::iter::FromIterator;
use std::io::{
BufRead,
Write
};
use std::vec::IntoIter;
use std::ops;
use Result;
#[derive(Debug)]
pub struct Buffer {
lines: Vec<String>,
cached_num_lines: usize,
modified: bool
}
trait InsertAll {
type Item;
fn insert_all<I: IntoIterator<Item=Self::Item>>(&mut self, pos: usize, insert: I) -> usize;
}
impl <T> InsertAll for Vec<T> {
type Item = T;
fn insert_all<I: IntoIterator<Item=Self::Item>>(&mut self, pos: usize, insert: I) -> usize {
let mut count = 0 as usize;
for (index, item) in insert.into_iter().enumerate() {
self.insert( pos + index, item );
count += 1;
}
count
}
}
impl FromIterator<String> for Buffer {
fn from_iter<T>(iter: T) -> Buffer
where T: IntoIterator<Item=String> {
let mut buffer = Buffer::new();
buffer.insert_lines(0, iter);
return buffer
}
}
impl IntoIterator for Buffer {
type Item = String;
type IntoIter = IntoIter<String>;
fn into_iter(self) -> Self::IntoIter {
self.lines.into_iter()
}
}
impl Buffer {
pub fn new() -> Buffer {
Buffer {
lines: Vec::new(),
cached_num_lines: 0 as usize,
modified: false
}
}
pub fn | <R: BufRead + Sized> (buf_read: R) -> Result<Buffer> {
let lines = buf_read.lines();
let lines_vec = lines.map(|r| r.unwrap()).collect::<Vec<String>>();
let cached_len = lines_vec.len();
Ok(Buffer {
lines: lines_vec,
cached_num_lines: cached_len,
modified: false
})
}
pub fn insert_lines<I: IntoIterator<Item=String>>(&mut self, pos: usize, insert: I) {
let added_lines = self.lines.insert_all(pos, insert);
self.cached_num_lines += added_lines;
self.modified = true;
}
pub fn insert_buffer(&mut self, pos: usize, buffer: Buffer) {
self.lines.insert_all(pos, buffer.lines);
self.cached_num_lines += buffer.cached_num_lines;
self.modified = true;
}
pub fn add_line(&mut self, line: String) {
self.lines.push(line);
self.cached_num_lines += 1;
self.modified = true;
}
pub fn delete_lines(&mut self, start: usize, end: usize) {
for _ in start..end {
self.lines.remove(start);
}
self.cached_num_lines -= end - start;
}
pub fn is_empty(&self) -> bool {
self.cached_num_lines == 0
}
pub fn has_changes(&self) -> bool {
self.modified
}
pub fn len(&self) -> usize {
self.cached_num_lines
}
pub fn is_out_of_bounds(&self, pos: usize) -> bool {
pos > self.len()
}
pub fn is_range_out_of_bounds(&self, range: &ops::Range<usize>) -> bool {
self.is_out_of_bounds(range.start) || self.is_out_of_bounds(range.end)
}
pub fn get_lines(&self, range: &ops::Range<usize>) -> &[String] {
assert!(! self.is_out_of_bounds( range.start ), format!("Out of bounds: {}/0", range.start) );
assert!(! self.is_out_of_bounds( range.end ), format!("Out of bounds: {}/{}", range.end, self.len()) );
&self.lines[ range.start.. range.end ]
}
pub fn write<W: Write>(&self, w:&mut W) -> Result<()> {
for line in self.lines.iter() {
try!( w.write_all( line.as_bytes() ) );
}
Ok(())
}
}
| from_buf_read | identifier_name |
buffer.rs |
use std::iter::FromIterator;
use std::io::{
BufRead,
Write
};
use std::vec::IntoIter;
use std::ops;
use Result;
#[derive(Debug)]
pub struct Buffer {
lines: Vec<String>,
cached_num_lines: usize,
modified: bool
}
trait InsertAll {
type Item;
fn insert_all<I: IntoIterator<Item=Self::Item>>(&mut self, pos: usize, insert: I) -> usize;
}
impl <T> InsertAll for Vec<T> {
type Item = T;
fn insert_all<I: IntoIterator<Item=Self::Item>>(&mut self, pos: usize, insert: I) -> usize {
let mut count = 0 as usize;
for (index, item) in insert.into_iter().enumerate() {
self.insert( pos + index, item );
count += 1;
}
count
}
}
impl FromIterator<String> for Buffer {
fn from_iter<T>(iter: T) -> Buffer
where T: IntoIterator<Item=String> {
let mut buffer = Buffer::new();
buffer.insert_lines(0, iter);
return buffer
}
}
impl IntoIterator for Buffer {
type Item = String;
type IntoIter = IntoIter<String>;
fn into_iter(self) -> Self::IntoIter {
self.lines.into_iter()
}
}
impl Buffer {
pub fn new() -> Buffer {
Buffer {
lines: Vec::new(),
cached_num_lines: 0 as usize,
modified: false
}
}
pub fn from_buf_read<R: BufRead + Sized> (buf_read: R) -> Result<Buffer> {
let lines = buf_read.lines();
let lines_vec = lines.map(|r| r.unwrap()).collect::<Vec<String>>();
let cached_len = lines_vec.len();
Ok(Buffer {
lines: lines_vec,
cached_num_lines: cached_len,
modified: false
})
}
pub fn insert_lines<I: IntoIterator<Item=String>>(&mut self, pos: usize, insert: I) {
let added_lines = self.lines.insert_all(pos, insert);
self.cached_num_lines += added_lines;
self.modified = true;
}
pub fn insert_buffer(&mut self, pos: usize, buffer: Buffer) {
self.lines.insert_all(pos, buffer.lines);
self.cached_num_lines += buffer.cached_num_lines;
self.modified = true;
}
pub fn add_line(&mut self, line: String) {
self.lines.push(line);
self.cached_num_lines += 1;
self.modified = true;
}
pub fn delete_lines(&mut self, start: usize, end: usize) {
for _ in start..end {
self.lines.remove(start);
}
self.cached_num_lines -= end - start;
}
pub fn is_empty(&self) -> bool {
self.cached_num_lines == 0
}
pub fn has_changes(&self) -> bool {
self.modified
}
pub fn len(&self) -> usize {
self.cached_num_lines
}
pub fn is_out_of_bounds(&self, pos: usize) -> bool {
pos > self.len()
}
pub fn is_range_out_of_bounds(&self, range: &ops::Range<usize>) -> bool |
pub fn get_lines(&self, range: &ops::Range<usize>) -> &[String] {
assert!(! self.is_out_of_bounds( range.start ), format!("Out of bounds: {}/0", range.start) );
assert!(! self.is_out_of_bounds( range.end ), format!("Out of bounds: {}/{}", range.end, self.len()) );
&self.lines[ range.start.. range.end ]
}
pub fn write<W: Write>(&self, w:&mut W) -> Result<()> {
for line in self.lines.iter() {
try!( w.write_all( line.as_bytes() ) );
}
Ok(())
}
}
| {
self.is_out_of_bounds(range.start) || self.is_out_of_bounds(range.end)
} | identifier_body |
float_macros.rs | // 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.
#![doc(hidden)]
macro_rules! assert_approx_eq {
($a:expr, $b:expr) => ({
use num::Float;
let (a, b) = (&$a, &$b);
assert!((*a - *b).abs() < 1.0e-6,
"{} is not approximately equal to {}", *a, *b);
})
}
macro_rules! from_str_radix_float_impl {
($T:ty) => {
fn from_str_radix(src: &str, radix: u32)
-> Result<$T, ParseFloatError> {
use num::FloatErrorKind::*;
use num::ParseFloatError as PFE;
// Special values
match src {
"inf" => return Ok(Float::infinity()),
"-inf" => return Ok(Float::neg_infinity()),
"NaN" => return Ok(Float::nan()),
_ => {},
}
let (is_positive, src) = match src.slice_shift_char() {
None => return Err(PFE { __kind: Empty }),
Some(('-', "")) => return Err(PFE { __kind: Empty }),
Some(('-', src)) => (false, src),
Some((_, _)) => (true, src),
};
// The significand to accumulate
let mut sig = if is_positive { 0.0 } else { -0.0 };
// Necessary to detect overflow
let mut prev_sig = sig;
let mut cs = src.chars().enumerate();
// Exponent prefix and exponent index offset
let mut exp_info = None::<(char, usize)>;
// Parse the integer part of the significand
for (i, c) in cs.by_ref() {
match c.to_digit(radix) {
Some(digit) => {
// shift significand one digit left
sig = sig * (radix as $T);
// add/subtract current digit depending on sign
if is_positive {
sig = sig + ((digit as isize) as $T);
} else {
sig = sig - ((digit as isize) as $T);
}
// Detect overflow by comparing to last value, except
// if we've not seen any non-zero digits.
if prev_sig!= 0.0 {
if is_positive && sig <= prev_sig
{ return Ok(Float::infinity()); }
if!is_positive && sig >= prev_sig
{ return Ok(Float::neg_infinity()); }
// Detect overflow by reversing the shift-and-add process
if is_positive && (prev_sig!= (sig - digit as $T) / radix as $T)
{ return Ok(Float::infinity()); }
if!is_positive && (prev_sig!= (sig + digit as $T) / radix as $T)
{ return Ok(Float::neg_infinity()); }
}
prev_sig = sig;
},
None => match c {
'e' | 'E' | 'p' | 'P' => {
exp_info = Some((c, i + 1));
break; // start of exponent
},
'.' => {
break; // start of fractional part
},
_ => {
return Err(PFE { __kind: Invalid }); | }
// If we are not yet at the exponent parse the fractional
// part of the significand
if exp_info.is_none() {
let mut power = 1.0;
for (i, c) in cs.by_ref() {
match c.to_digit(radix) {
Some(digit) => {
// Decrease power one order of magnitude
power = power / (radix as $T);
// add/subtract current digit depending on sign
sig = if is_positive {
sig + (digit as $T) * power
} else {
sig - (digit as $T) * power
};
// Detect overflow by comparing to last value
if is_positive && sig < prev_sig
{ return Ok(Float::infinity()); }
if!is_positive && sig > prev_sig
{ return Ok(Float::neg_infinity()); }
prev_sig = sig;
},
None => match c {
'e' | 'E' | 'p' | 'P' => {
exp_info = Some((c, i + 1));
break; // start of exponent
},
_ => {
return Err(PFE { __kind: Invalid });
},
},
}
}
}
// Parse and calculate the exponent
let exp = match exp_info {
Some((c, offset)) => {
let base = match c {
'E' | 'e' if radix == 10 => 10.0,
'P' | 'p' if radix == 16 => 2.0,
_ => return Err(PFE { __kind: Invalid }),
};
// Parse the exponent as decimal integer
let src = &src[offset..];
let (is_positive, exp) = match src.slice_shift_char() {
Some(('-', src)) => (false, src.parse::<usize>()),
Some(('+', src)) => (true, src.parse::<usize>()),
Some((_, _)) => (true, src.parse::<usize>()),
None => return Err(PFE { __kind: Invalid }),
};
match (is_positive, exp) {
(true, Ok(exp)) => base.powi(exp as i32),
(false, Ok(exp)) => 1.0 / base.powi(exp as i32),
(_, Err(_)) => return Err(PFE { __kind: Invalid }),
}
},
None => 1.0, // no exponent
};
Ok(sig * exp)
}
}
} | },
},
} | random_line_split |
htmltablecellelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use cssparser::RGBA;
use dom::attr::{Attr, AttrValue};
use dom::bindings::codegen::Bindings::HTMLTableCellElementBinding::HTMLTableCellElementMethods;
use dom::bindings::codegen::Bindings::NodeBinding::NodeMethods;
use dom::bindings::inheritance::Castable;
use dom::bindings::js::LayoutJS;
use dom::document::Document;
use dom::element::{AttributeMutation, Element, RawLayoutElementHelpers};
use dom::htmlelement::HTMLElement;
use dom::htmltablerowelement::HTMLTableRowElement;
use dom::node::Node;
use dom::virtualmethods::VirtualMethods;
use std::cell::Cell;
use string_cache::Atom;
use util::str::{self, DOMString, LengthOrPercentageOrAuto};
const DEFAULT_COLSPAN: u32 = 1;
#[dom_struct]
pub struct HTMLTableCellElement {
htmlelement: HTMLElement,
width: Cell<LengthOrPercentageOrAuto>,
}
impl HTMLTableCellElement {
pub fn new_inherited(tag_name: DOMString,
prefix: Option<DOMString>,
document: &Document)
-> HTMLTableCellElement {
HTMLTableCellElement {
htmlelement: HTMLElement::new_inherited(tag_name, prefix, document),
width: Cell::new(LengthOrPercentageOrAuto::Auto),
}
}
#[inline]
pub fn htmlelement(&self) -> &HTMLElement {
&self.htmlelement
}
}
impl HTMLTableCellElementMethods for HTMLTableCellElement {
// https://html.spec.whatwg.org/multipage/#dom-tdth-colspan
make_uint_getter!(ColSpan, "colspan", DEFAULT_COLSPAN);
// https://html.spec.whatwg.org/multipage/#dom-tdth-colspan
make_uint_setter!(SetColSpan, "colspan", DEFAULT_COLSPAN);
// https://html.spec.whatwg.org/multipage/#dom-tdth-bgcolor
make_getter!(BgColor, "bgcolor");
// https://html.spec.whatwg.org/multipage/#dom-tdth-bgcolor
make_legacy_color_setter!(SetBgColor, "bgcolor");
// https://html.spec.whatwg.org/multipage/#dom-tdth-cellindex
fn CellIndex(&self) -> i32 {
let self_node = self.upcast::<Node>();
let parent_children = match self_node.GetParentNode() {
Some(ref parent_node) if parent_node.is::<HTMLTableRowElement>() => {
parent_node.children()
},
_ => return -1,
};
parent_children.filter(|c| c.is::<HTMLTableCellElement>())
.position(|c| c.r() == self_node)
.map(|p| p as i32).unwrap_or(-1)
}
}
pub trait HTMLTableCellElementLayoutHelpers {
fn get_background_color(&self) -> Option<RGBA>;
fn get_colspan(&self) -> Option<u32>;
fn get_width(&self) -> LengthOrPercentageOrAuto;
}
#[allow(unsafe_code)]
impl HTMLTableCellElementLayoutHelpers for LayoutJS<HTMLTableCellElement> {
fn get_background_color(&self) -> Option<RGBA> {
unsafe {
(&*self.upcast::<Element>().unsafe_get())
.get_attr_for_layout(&ns!(), &atom!("bgcolor"))
.and_then(AttrValue::as_color)
.cloned()
}
}
fn | (&self) -> Option<u32> {
unsafe {
(&*self.upcast::<Element>().unsafe_get())
.get_attr_for_layout(&ns!(), &atom!("colspan"))
.map(AttrValue::as_uint)
}
}
fn get_width(&self) -> LengthOrPercentageOrAuto {
unsafe {
(*self.unsafe_get()).width.get()
}
}
}
impl VirtualMethods for HTMLTableCellElement {
fn super_type(&self) -> Option<&VirtualMethods> {
Some(self.upcast::<HTMLElement>() as &VirtualMethods)
}
fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) {
self.super_type().unwrap().attribute_mutated(attr, mutation);
match *attr.local_name() {
atom!("width") => {
let width = mutation.new_value(attr).map(|value| {
str::parse_length(&value)
});
self.width.set(width.unwrap_or(LengthOrPercentageOrAuto::Auto));
},
_ => {},
}
}
fn parse_plain_attribute(&self, local_name: &Atom, value: DOMString) -> AttrValue {
match *local_name {
atom!("colspan") => AttrValue::from_u32(value, DEFAULT_COLSPAN),
atom!("bgcolor") => AttrValue::from_legacy_color(value),
_ => self.super_type().unwrap().parse_plain_attribute(local_name, value),
}
}
}
| get_colspan | identifier_name |
htmltablecellelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use cssparser::RGBA;
use dom::attr::{Attr, AttrValue};
use dom::bindings::codegen::Bindings::HTMLTableCellElementBinding::HTMLTableCellElementMethods;
use dom::bindings::codegen::Bindings::NodeBinding::NodeMethods;
use dom::bindings::inheritance::Castable;
use dom::bindings::js::LayoutJS;
use dom::document::Document;
use dom::element::{AttributeMutation, Element, RawLayoutElementHelpers};
use dom::htmlelement::HTMLElement;
use dom::htmltablerowelement::HTMLTableRowElement;
use dom::node::Node;
use dom::virtualmethods::VirtualMethods;
use std::cell::Cell;
use string_cache::Atom;
use util::str::{self, DOMString, LengthOrPercentageOrAuto};
const DEFAULT_COLSPAN: u32 = 1;
#[dom_struct]
pub struct HTMLTableCellElement {
htmlelement: HTMLElement,
width: Cell<LengthOrPercentageOrAuto>,
}
impl HTMLTableCellElement {
pub fn new_inherited(tag_name: DOMString,
prefix: Option<DOMString>,
document: &Document)
-> HTMLTableCellElement {
HTMLTableCellElement {
htmlelement: HTMLElement::new_inherited(tag_name, prefix, document),
width: Cell::new(LengthOrPercentageOrAuto::Auto),
}
}
#[inline]
pub fn htmlelement(&self) -> &HTMLElement {
&self.htmlelement
}
}
impl HTMLTableCellElementMethods for HTMLTableCellElement {
// https://html.spec.whatwg.org/multipage/#dom-tdth-colspan
make_uint_getter!(ColSpan, "colspan", DEFAULT_COLSPAN);
// https://html.spec.whatwg.org/multipage/#dom-tdth-colspan
make_uint_setter!(SetColSpan, "colspan", DEFAULT_COLSPAN);
// https://html.spec.whatwg.org/multipage/#dom-tdth-bgcolor
make_getter!(BgColor, "bgcolor");
// https://html.spec.whatwg.org/multipage/#dom-tdth-bgcolor
make_legacy_color_setter!(SetBgColor, "bgcolor");
// https://html.spec.whatwg.org/multipage/#dom-tdth-cellindex
fn CellIndex(&self) -> i32 |
}
pub trait HTMLTableCellElementLayoutHelpers {
fn get_background_color(&self) -> Option<RGBA>;
fn get_colspan(&self) -> Option<u32>;
fn get_width(&self) -> LengthOrPercentageOrAuto;
}
#[allow(unsafe_code)]
impl HTMLTableCellElementLayoutHelpers for LayoutJS<HTMLTableCellElement> {
fn get_background_color(&self) -> Option<RGBA> {
unsafe {
(&*self.upcast::<Element>().unsafe_get())
.get_attr_for_layout(&ns!(), &atom!("bgcolor"))
.and_then(AttrValue::as_color)
.cloned()
}
}
fn get_colspan(&self) -> Option<u32> {
unsafe {
(&*self.upcast::<Element>().unsafe_get())
.get_attr_for_layout(&ns!(), &atom!("colspan"))
.map(AttrValue::as_uint)
}
}
fn get_width(&self) -> LengthOrPercentageOrAuto {
unsafe {
(*self.unsafe_get()).width.get()
}
}
}
impl VirtualMethods for HTMLTableCellElement {
fn super_type(&self) -> Option<&VirtualMethods> {
Some(self.upcast::<HTMLElement>() as &VirtualMethods)
}
fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) {
self.super_type().unwrap().attribute_mutated(attr, mutation);
match *attr.local_name() {
atom!("width") => {
let width = mutation.new_value(attr).map(|value| {
str::parse_length(&value)
});
self.width.set(width.unwrap_or(LengthOrPercentageOrAuto::Auto));
},
_ => {},
}
}
fn parse_plain_attribute(&self, local_name: &Atom, value: DOMString) -> AttrValue {
match *local_name {
atom!("colspan") => AttrValue::from_u32(value, DEFAULT_COLSPAN),
atom!("bgcolor") => AttrValue::from_legacy_color(value),
_ => self.super_type().unwrap().parse_plain_attribute(local_name, value),
}
}
}
| {
let self_node = self.upcast::<Node>();
let parent_children = match self_node.GetParentNode() {
Some(ref parent_node) if parent_node.is::<HTMLTableRowElement>() => {
parent_node.children()
},
_ => return -1,
};
parent_children.filter(|c| c.is::<HTMLTableCellElement>())
.position(|c| c.r() == self_node)
.map(|p| p as i32).unwrap_or(-1)
} | identifier_body |
htmltablecellelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use cssparser::RGBA;
use dom::attr::{Attr, AttrValue};
use dom::bindings::codegen::Bindings::HTMLTableCellElementBinding::HTMLTableCellElementMethods;
use dom::bindings::codegen::Bindings::NodeBinding::NodeMethods;
use dom::bindings::inheritance::Castable;
use dom::bindings::js::LayoutJS;
use dom::document::Document;
use dom::element::{AttributeMutation, Element, RawLayoutElementHelpers};
use dom::htmlelement::HTMLElement;
use dom::htmltablerowelement::HTMLTableRowElement;
use dom::node::Node;
use dom::virtualmethods::VirtualMethods;
use std::cell::Cell;
use string_cache::Atom;
use util::str::{self, DOMString, LengthOrPercentageOrAuto};
const DEFAULT_COLSPAN: u32 = 1;
#[dom_struct]
pub struct HTMLTableCellElement {
htmlelement: HTMLElement,
width: Cell<LengthOrPercentageOrAuto>,
}
impl HTMLTableCellElement {
pub fn new_inherited(tag_name: DOMString,
prefix: Option<DOMString>,
document: &Document)
-> HTMLTableCellElement {
HTMLTableCellElement {
htmlelement: HTMLElement::new_inherited(tag_name, prefix, document),
width: Cell::new(LengthOrPercentageOrAuto::Auto),
}
}
#[inline]
pub fn htmlelement(&self) -> &HTMLElement {
&self.htmlelement
}
}
impl HTMLTableCellElementMethods for HTMLTableCellElement {
// https://html.spec.whatwg.org/multipage/#dom-tdth-colspan
make_uint_getter!(ColSpan, "colspan", DEFAULT_COLSPAN);
// https://html.spec.whatwg.org/multipage/#dom-tdth-colspan
make_uint_setter!(SetColSpan, "colspan", DEFAULT_COLSPAN);
// https://html.spec.whatwg.org/multipage/#dom-tdth-bgcolor
make_getter!(BgColor, "bgcolor");
// https://html.spec.whatwg.org/multipage/#dom-tdth-bgcolor
make_legacy_color_setter!(SetBgColor, "bgcolor");
// https://html.spec.whatwg.org/multipage/#dom-tdth-cellindex
fn CellIndex(&self) -> i32 {
let self_node = self.upcast::<Node>();
let parent_children = match self_node.GetParentNode() {
Some(ref parent_node) if parent_node.is::<HTMLTableRowElement>() => {
parent_node.children()
},
_ => return -1,
};
parent_children.filter(|c| c.is::<HTMLTableCellElement>())
.position(|c| c.r() == self_node)
.map(|p| p as i32).unwrap_or(-1)
}
}
pub trait HTMLTableCellElementLayoutHelpers {
fn get_background_color(&self) -> Option<RGBA>;
fn get_colspan(&self) -> Option<u32>;
fn get_width(&self) -> LengthOrPercentageOrAuto;
}
#[allow(unsafe_code)]
impl HTMLTableCellElementLayoutHelpers for LayoutJS<HTMLTableCellElement> {
fn get_background_color(&self) -> Option<RGBA> {
unsafe {
(&*self.upcast::<Element>().unsafe_get())
.get_attr_for_layout(&ns!(), &atom!("bgcolor"))
.and_then(AttrValue::as_color)
.cloned()
}
}
fn get_colspan(&self) -> Option<u32> {
unsafe {
(&*self.upcast::<Element>().unsafe_get())
.get_attr_for_layout(&ns!(), &atom!("colspan"))
.map(AttrValue::as_uint)
}
}
fn get_width(&self) -> LengthOrPercentageOrAuto {
unsafe {
(*self.unsafe_get()).width.get()
}
}
}
impl VirtualMethods for HTMLTableCellElement {
fn super_type(&self) -> Option<&VirtualMethods> {
Some(self.upcast::<HTMLElement>() as &VirtualMethods)
}
fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) { | match *attr.local_name() {
atom!("width") => {
let width = mutation.new_value(attr).map(|value| {
str::parse_length(&value)
});
self.width.set(width.unwrap_or(LengthOrPercentageOrAuto::Auto));
},
_ => {},
}
}
fn parse_plain_attribute(&self, local_name: &Atom, value: DOMString) -> AttrValue {
match *local_name {
atom!("colspan") => AttrValue::from_u32(value, DEFAULT_COLSPAN),
atom!("bgcolor") => AttrValue::from_legacy_color(value),
_ => self.super_type().unwrap().parse_plain_attribute(local_name, value),
}
}
} | self.super_type().unwrap().attribute_mutated(attr, mutation); | random_line_split |
issue-1112.rs | // Copyright 2012 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.
// Issue #1112
// Alignment of interior pointers to dynamic-size types
struct X<T> {
a: T,
b: u8,
c: bool,
d: u8,
e: u16,
f: u8,
g: u8
}
pub fn main() {
let x: X<isize> = X {
a: 12345678,
b: 9,
c: true,
d: 10,
e: 11,
f: 12,
g: 13
};
bar(x);
}
fn | <T>(x: X<T>) {
assert_eq!(x.b, 9);
assert_eq!(x.c, true);
assert_eq!(x.d, 10);
assert_eq!(x.e, 11);
assert_eq!(x.f, 12);
assert_eq!(x.g, 13);
}
| bar | identifier_name |
issue-1112.rs | // Copyright 2012 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.
// Issue #1112
// Alignment of interior pointers to dynamic-size types
struct X<T> {
a: T,
b: u8,
c: bool,
d: u8,
e: u16,
f: u8,
g: u8
}
pub fn main() {
let x: X<isize> = X {
a: 12345678,
b: 9,
c: true,
d: 10,
e: 11,
f: 12,
g: 13
};
bar(x);
} | assert_eq!(x.e, 11);
assert_eq!(x.f, 12);
assert_eq!(x.g, 13);
} |
fn bar<T>(x: X<T>) {
assert_eq!(x.b, 9);
assert_eq!(x.c, true);
assert_eq!(x.d, 10); | random_line_split |
inherit-struct2.rs | // 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.
// Test struct inheritance on structs from another crate.
// aux-build:inherit_struct_lib.rs
extern crate inherit_struct_lib;
pub fn main() {
let s = inherit_struct_lib::S2{f1: 115, f2: 113};
assert!(s.f1 == 115);
assert!(s.f2 == 113);
assert!(inherit_struct_lib::glob_s.f1 == 32);
assert!(inherit_struct_lib::glob_s.f2 == -45);
inherit_struct_lib::test_s2(s);
} | random_line_split | |
inherit-struct2.rs | // 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.
// Test struct inheritance on structs from another crate.
// aux-build:inherit_struct_lib.rs
extern crate inherit_struct_lib;
pub fn main() | {
let s = inherit_struct_lib::S2{f1: 115, f2: 113};
assert!(s.f1 == 115);
assert!(s.f2 == 113);
assert!(inherit_struct_lib::glob_s.f1 == 32);
assert!(inherit_struct_lib::glob_s.f2 == -45);
inherit_struct_lib::test_s2(s);
} | identifier_body | |
inherit-struct2.rs | // 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.
// Test struct inheritance on structs from another crate.
// aux-build:inherit_struct_lib.rs
extern crate inherit_struct_lib;
pub fn | () {
let s = inherit_struct_lib::S2{f1: 115, f2: 113};
assert!(s.f1 == 115);
assert!(s.f2 == 113);
assert!(inherit_struct_lib::glob_s.f1 == 32);
assert!(inherit_struct_lib::glob_s.f2 == -45);
inherit_struct_lib::test_s2(s);
}
| main | identifier_name |
server.rs | #![feature(core)]
extern crate eve;
extern crate getopts;
extern crate url;
extern crate core;
use std::thread;
use std::env;
use getopts::Options;
use std::net::SocketAddr;
use core::str::FromStr;
use eve::server;
use eve::login;
#[allow(dead_code)]
fn main() { |
// handle command line arguments
let args: Vec<String> = env::args().collect();
// define the command line arguments
let mut opts = Options::new();
opts.optopt("f", "faddress", "specify a socket address for the static file server. Defaults to 0.0.0.0:8080","SOCKET ADDRESS");
opts.optflag("h", "help", "prints all options and usage");
// parse raw input arguments into options
let matches = match opts.parse(&args[1..]) {
Ok(m) => { m }
Err(f) => { panic!(f.to_string()) }
};
// print the help menu
if matches.opt_present("h") {
print!("{}", opts.usage(""));
return;
}
// parse static file server address
let default_addr= SocketAddr::from_str("0.0.0.0:8080").unwrap();
let addr = match matches.opt_str("f") {
Some(ip) => {
match SocketAddr::from_str(&*ip) {
Ok(addr) => addr,
Err(_) => {
println!("WARNING: Could not parse static file server address.\nDefaulting to {:?}",default_addr);
default_addr
}
}
},
None => default_addr,
};
thread::spawn(move || login::run(addr.clone()));
server::run();
} | random_line_split | |
server.rs | #![feature(core)]
extern crate eve;
extern crate getopts;
extern crate url;
extern crate core;
use std::thread;
use std::env;
use getopts::Options;
use std::net::SocketAddr;
use core::str::FromStr;
use eve::server;
use eve::login;
#[allow(dead_code)]
fn main() | }
// parse static file server address
let default_addr= SocketAddr::from_str("0.0.0.0:8080").unwrap();
let addr = match matches.opt_str("f") {
Some(ip) => {
match SocketAddr::from_str(&*ip) {
Ok(addr) => addr,
Err(_) => {
println!("WARNING: Could not parse static file server address.\nDefaulting to {:?}",default_addr);
default_addr
}
}
},
None => default_addr,
};
thread::spawn(move || login::run(addr.clone()));
server::run();
} | {
// handle command line arguments
let args: Vec<String> = env::args().collect();
// define the command line arguments
let mut opts = Options::new();
opts.optopt("f", "faddress", "specify a socket address for the static file server. Defaults to 0.0.0.0:8080","SOCKET ADDRESS");
opts.optflag("h", "help", "prints all options and usage");
// parse raw input arguments into options
let matches = match opts.parse(&args[1..]) {
Ok(m) => { m }
Err(f) => { panic!(f.to_string()) }
};
// print the help menu
if matches.opt_present("h") {
print!("{}", opts.usage(""));
return; | identifier_body |
server.rs | #![feature(core)]
extern crate eve;
extern crate getopts;
extern crate url;
extern crate core;
use std::thread;
use std::env;
use getopts::Options;
use std::net::SocketAddr;
use core::str::FromStr;
use eve::server;
use eve::login;
#[allow(dead_code)]
fn | () {
// handle command line arguments
let args: Vec<String> = env::args().collect();
// define the command line arguments
let mut opts = Options::new();
opts.optopt("f", "faddress", "specify a socket address for the static file server. Defaults to 0.0.0.0:8080","SOCKET ADDRESS");
opts.optflag("h", "help", "prints all options and usage");
// parse raw input arguments into options
let matches = match opts.parse(&args[1..]) {
Ok(m) => { m }
Err(f) => { panic!(f.to_string()) }
};
// print the help menu
if matches.opt_present("h") {
print!("{}", opts.usage(""));
return;
}
// parse static file server address
let default_addr= SocketAddr::from_str("0.0.0.0:8080").unwrap();
let addr = match matches.opt_str("f") {
Some(ip) => {
match SocketAddr::from_str(&*ip) {
Ok(addr) => addr,
Err(_) => {
println!("WARNING: Could not parse static file server address.\nDefaulting to {:?}",default_addr);
default_addr
}
}
},
None => default_addr,
};
thread::spawn(move || login::run(addr.clone()));
server::run();
} | main | identifier_name |
irq.rs | use ::kern::arch::port::{UnsafePort, Port};
use spin::Mutex;
/**
* ref: http://wiki.osdev.org/8259_PIC
*/
const PIC1_BASE: u16 = 0x20; /* IO base address for master PIC */
const PIC2_BASE: u16 = 0xA0; /* IO base address for slave PIC */
// Initial IRQ mask has interrupt 2 enabled (for slave 8259A).
const IRQ_MASK: u16 = 0xffff &!(1<<2);
/// vector numbers for IRQs
#[derive(Debug, Clone, Copy)]
#[allow(dead_code)]
pub enum Irqs {
TIMER = 32, // PIT
KBD = 33,
IRQ2 = 34, // slave
IRQ3 = 35, // serial2
IRQ4 = 36, // serial1
IRQ5 = 37, // LPT2
IRQ6 = 38, // floppy
IRQ7 = 39, // LPT1
IRQ8 = 40, // RTC
IRQ9 = 41, // IRQ2
IRQ10 = 42, // reserve
IRQ11 = 43, // reserve
MOUSE = 44, // PS/2 mouse
IRQ13 = 45, // FPU
ATA1 = 46, // ATA HD1
ATA2 = 47, // ATA HD2
}
///8259A chip
pub struct Pic8259A {
offset: u8,
command: UnsafePort<u8>,
data: UnsafePort<u8>
}
impl Pic8259A {
pub const unsafe fn new(base: u16, offset: u8) -> Pic8259A {
Pic8259A {
offset: offset,
command: UnsafePort::new(base),
data: UnsafePort::new(base+1)
}
}
pub unsafe fn eoi(&mut self) {
self.command.write(0x20);
}
}
/// represent two cascaded pic chips
pub struct PicChain {
pics: [Pic8259A; 2],
irqmask: u16
}
pub static PIC_CHAIN: Mutex<PicChain> = Mutex::new(unsafe {PicChain::new()});
/* reinitialize the PIC controllers, giving them specified vector offsets
rather than 8h and 70h, as configured by default */
const ICW1_ICW4: u8 = 0x01; /* ICW4 (not) needed */
#[allow(dead_code)]
const ICW1_SINGLE: u8 = 0x02; /* Single (cascade) mode */
#[allow(dead_code)]
const ICW1_INTERVAL4: u8 = 0x04; /* Call address interval 4 (8) */
#[allow(dead_code)]
const ICW1_LEVEL: u8 = 0x08; /* Level triggered (edge) mode */
#[allow(dead_code)]
const ICW1_INIT: u8 = 0x10; /* Initialization - required! */
const ICW4_8086: u8 = 0x01; /* 8086/88 (MCS-80/85) mode */
#[allow(dead_code)]
const ICW4_AUTO: u8 = 0x02; /* Auto (normal) EOI */
#[allow(dead_code)]
const ICW4_BUF_SLAVE: u8 = 0x08; /* Buffered mode/slave */
#[allow(dead_code)]
const ICW4_BUF_MASTER: u8 = 0x0C; /* Buffered mode/master */
#[allow(dead_code)]
const ICW4_SFNM: u8 = 0x10; /* Special fully nested (not) */
impl PicChain {
pub const unsafe fn new() -> PicChain {
PicChain {
pics: [
Pic8259A::new(PIC1_BASE, 0x20),
Pic8259A::new(PIC2_BASE, 0x28),
],
irqmask: IRQ_MASK
}
}
pub unsafe fn init(&mut self) {
let mut port80 = Port::new(0x80);
let mut io_wait = || port80.write(0 as u8); |
self.pics[1].command.write(ICW1_INIT + ICW1_ICW4);
io_wait();
self.pics[0].data.write(self.pics[0].offset);
io_wait();
self.pics[1].data.write(self.pics[1].offset);
io_wait();
// ICW3: tell Master PIC that there is a slave PIC at IRQ2
self.pics[0].data.write(0b0000_0100);
io_wait();
// ICW3: tell Slave PIC its cascade identity (0000 0010)
self.pics[1].data.write(0x2);
io_wait();
self.pics[0].data.write(ICW4_8086);
io_wait();
self.pics[1].data.write(ICW4_8086);
io_wait();
let mask =self.irqmask;
self.setmask(mask);
}
pub unsafe fn eoi(&mut self, isr: usize) {
assert!(isr < 0x10);
if isr >= 8 {
self.pics[1].eoi();
}
self.pics[0].eoi();
}
unsafe fn setmask(&mut self, mask: u16) {
self.irqmask = mask;
self.pics[0].data.write(mask as u8);
self.pics[1].data.write((mask >> 8) as u8);
}
pub unsafe fn enable(&mut self, irq: usize) {
assert!(irq >= 0x20 && irq < 0x30);
let irq = (irq - 0x20) as u16;
let mask = self.irqmask &!(1<<irq);
self.setmask(mask);
}
} |
self.pics[0].command.write(ICW1_INIT + ICW1_ICW4);
io_wait(); | random_line_split |
irq.rs | use ::kern::arch::port::{UnsafePort, Port};
use spin::Mutex;
/**
* ref: http://wiki.osdev.org/8259_PIC
*/
const PIC1_BASE: u16 = 0x20; /* IO base address for master PIC */
const PIC2_BASE: u16 = 0xA0; /* IO base address for slave PIC */
// Initial IRQ mask has interrupt 2 enabled (for slave 8259A).
const IRQ_MASK: u16 = 0xffff &!(1<<2);
/// vector numbers for IRQs
#[derive(Debug, Clone, Copy)]
#[allow(dead_code)]
pub enum Irqs {
TIMER = 32, // PIT
KBD = 33,
IRQ2 = 34, // slave
IRQ3 = 35, // serial2
IRQ4 = 36, // serial1
IRQ5 = 37, // LPT2
IRQ6 = 38, // floppy
IRQ7 = 39, // LPT1
IRQ8 = 40, // RTC
IRQ9 = 41, // IRQ2
IRQ10 = 42, // reserve
IRQ11 = 43, // reserve
MOUSE = 44, // PS/2 mouse
IRQ13 = 45, // FPU
ATA1 = 46, // ATA HD1
ATA2 = 47, // ATA HD2
}
///8259A chip
pub struct Pic8259A {
offset: u8,
command: UnsafePort<u8>,
data: UnsafePort<u8>
}
impl Pic8259A {
pub const unsafe fn new(base: u16, offset: u8) -> Pic8259A {
Pic8259A {
offset: offset,
command: UnsafePort::new(base),
data: UnsafePort::new(base+1)
}
}
pub unsafe fn eoi(&mut self) {
self.command.write(0x20);
}
}
/// represent two cascaded pic chips
pub struct PicChain {
pics: [Pic8259A; 2],
irqmask: u16
}
pub static PIC_CHAIN: Mutex<PicChain> = Mutex::new(unsafe {PicChain::new()});
/* reinitialize the PIC controllers, giving them specified vector offsets
rather than 8h and 70h, as configured by default */
const ICW1_ICW4: u8 = 0x01; /* ICW4 (not) needed */
#[allow(dead_code)]
const ICW1_SINGLE: u8 = 0x02; /* Single (cascade) mode */
#[allow(dead_code)]
const ICW1_INTERVAL4: u8 = 0x04; /* Call address interval 4 (8) */
#[allow(dead_code)]
const ICW1_LEVEL: u8 = 0x08; /* Level triggered (edge) mode */
#[allow(dead_code)]
const ICW1_INIT: u8 = 0x10; /* Initialization - required! */
const ICW4_8086: u8 = 0x01; /* 8086/88 (MCS-80/85) mode */
#[allow(dead_code)]
const ICW4_AUTO: u8 = 0x02; /* Auto (normal) EOI */
#[allow(dead_code)]
const ICW4_BUF_SLAVE: u8 = 0x08; /* Buffered mode/slave */
#[allow(dead_code)]
const ICW4_BUF_MASTER: u8 = 0x0C; /* Buffered mode/master */
#[allow(dead_code)]
const ICW4_SFNM: u8 = 0x10; /* Special fully nested (not) */
impl PicChain {
pub const unsafe fn new() -> PicChain {
PicChain {
pics: [
Pic8259A::new(PIC1_BASE, 0x20),
Pic8259A::new(PIC2_BASE, 0x28),
],
irqmask: IRQ_MASK
}
}
pub unsafe fn init(&mut self) {
let mut port80 = Port::new(0x80);
let mut io_wait = || port80.write(0 as u8);
self.pics[0].command.write(ICW1_INIT + ICW1_ICW4);
io_wait();
self.pics[1].command.write(ICW1_INIT + ICW1_ICW4);
io_wait();
self.pics[0].data.write(self.pics[0].offset);
io_wait();
self.pics[1].data.write(self.pics[1].offset);
io_wait();
// ICW3: tell Master PIC that there is a slave PIC at IRQ2
self.pics[0].data.write(0b0000_0100);
io_wait();
// ICW3: tell Slave PIC its cascade identity (0000 0010)
self.pics[1].data.write(0x2);
io_wait();
self.pics[0].data.write(ICW4_8086);
io_wait();
self.pics[1].data.write(ICW4_8086);
io_wait();
let mask =self.irqmask;
self.setmask(mask);
}
pub unsafe fn eoi(&mut self, isr: usize) {
assert!(isr < 0x10);
if isr >= 8 |
self.pics[0].eoi();
}
unsafe fn setmask(&mut self, mask: u16) {
self.irqmask = mask;
self.pics[0].data.write(mask as u8);
self.pics[1].data.write((mask >> 8) as u8);
}
pub unsafe fn enable(&mut self, irq: usize) {
assert!(irq >= 0x20 && irq < 0x30);
let irq = (irq - 0x20) as u16;
let mask = self.irqmask &!(1<<irq);
self.setmask(mask);
}
}
| {
self.pics[1].eoi();
} | conditional_block |
irq.rs | use ::kern::arch::port::{UnsafePort, Port};
use spin::Mutex;
/**
* ref: http://wiki.osdev.org/8259_PIC
*/
const PIC1_BASE: u16 = 0x20; /* IO base address for master PIC */
const PIC2_BASE: u16 = 0xA0; /* IO base address for slave PIC */
// Initial IRQ mask has interrupt 2 enabled (for slave 8259A).
const IRQ_MASK: u16 = 0xffff &!(1<<2);
/// vector numbers for IRQs
#[derive(Debug, Clone, Copy)]
#[allow(dead_code)]
pub enum Irqs {
TIMER = 32, // PIT
KBD = 33,
IRQ2 = 34, // slave
IRQ3 = 35, // serial2
IRQ4 = 36, // serial1
IRQ5 = 37, // LPT2
IRQ6 = 38, // floppy
IRQ7 = 39, // LPT1
IRQ8 = 40, // RTC
IRQ9 = 41, // IRQ2
IRQ10 = 42, // reserve
IRQ11 = 43, // reserve
MOUSE = 44, // PS/2 mouse
IRQ13 = 45, // FPU
ATA1 = 46, // ATA HD1
ATA2 = 47, // ATA HD2
}
///8259A chip
pub struct Pic8259A {
offset: u8,
command: UnsafePort<u8>,
data: UnsafePort<u8>
}
impl Pic8259A {
pub const unsafe fn new(base: u16, offset: u8) -> Pic8259A {
Pic8259A {
offset: offset,
command: UnsafePort::new(base),
data: UnsafePort::new(base+1)
}
}
pub unsafe fn eoi(&mut self) |
}
/// represent two cascaded pic chips
pub struct PicChain {
pics: [Pic8259A; 2],
irqmask: u16
}
pub static PIC_CHAIN: Mutex<PicChain> = Mutex::new(unsafe {PicChain::new()});
/* reinitialize the PIC controllers, giving them specified vector offsets
rather than 8h and 70h, as configured by default */
const ICW1_ICW4: u8 = 0x01; /* ICW4 (not) needed */
#[allow(dead_code)]
const ICW1_SINGLE: u8 = 0x02; /* Single (cascade) mode */
#[allow(dead_code)]
const ICW1_INTERVAL4: u8 = 0x04; /* Call address interval 4 (8) */
#[allow(dead_code)]
const ICW1_LEVEL: u8 = 0x08; /* Level triggered (edge) mode */
#[allow(dead_code)]
const ICW1_INIT: u8 = 0x10; /* Initialization - required! */
const ICW4_8086: u8 = 0x01; /* 8086/88 (MCS-80/85) mode */
#[allow(dead_code)]
const ICW4_AUTO: u8 = 0x02; /* Auto (normal) EOI */
#[allow(dead_code)]
const ICW4_BUF_SLAVE: u8 = 0x08; /* Buffered mode/slave */
#[allow(dead_code)]
const ICW4_BUF_MASTER: u8 = 0x0C; /* Buffered mode/master */
#[allow(dead_code)]
const ICW4_SFNM: u8 = 0x10; /* Special fully nested (not) */
impl PicChain {
pub const unsafe fn new() -> PicChain {
PicChain {
pics: [
Pic8259A::new(PIC1_BASE, 0x20),
Pic8259A::new(PIC2_BASE, 0x28),
],
irqmask: IRQ_MASK
}
}
pub unsafe fn init(&mut self) {
let mut port80 = Port::new(0x80);
let mut io_wait = || port80.write(0 as u8);
self.pics[0].command.write(ICW1_INIT + ICW1_ICW4);
io_wait();
self.pics[1].command.write(ICW1_INIT + ICW1_ICW4);
io_wait();
self.pics[0].data.write(self.pics[0].offset);
io_wait();
self.pics[1].data.write(self.pics[1].offset);
io_wait();
// ICW3: tell Master PIC that there is a slave PIC at IRQ2
self.pics[0].data.write(0b0000_0100);
io_wait();
// ICW3: tell Slave PIC its cascade identity (0000 0010)
self.pics[1].data.write(0x2);
io_wait();
self.pics[0].data.write(ICW4_8086);
io_wait();
self.pics[1].data.write(ICW4_8086);
io_wait();
let mask =self.irqmask;
self.setmask(mask);
}
pub unsafe fn eoi(&mut self, isr: usize) {
assert!(isr < 0x10);
if isr >= 8 {
self.pics[1].eoi();
}
self.pics[0].eoi();
}
unsafe fn setmask(&mut self, mask: u16) {
self.irqmask = mask;
self.pics[0].data.write(mask as u8);
self.pics[1].data.write((mask >> 8) as u8);
}
pub unsafe fn enable(&mut self, irq: usize) {
assert!(irq >= 0x20 && irq < 0x30);
let irq = (irq - 0x20) as u16;
let mask = self.irqmask &!(1<<irq);
self.setmask(mask);
}
}
| {
self.command.write(0x20);
} | identifier_body |
irq.rs | use ::kern::arch::port::{UnsafePort, Port};
use spin::Mutex;
/**
* ref: http://wiki.osdev.org/8259_PIC
*/
const PIC1_BASE: u16 = 0x20; /* IO base address for master PIC */
const PIC2_BASE: u16 = 0xA0; /* IO base address for slave PIC */
// Initial IRQ mask has interrupt 2 enabled (for slave 8259A).
const IRQ_MASK: u16 = 0xffff &!(1<<2);
/// vector numbers for IRQs
#[derive(Debug, Clone, Copy)]
#[allow(dead_code)]
pub enum Irqs {
TIMER = 32, // PIT
KBD = 33,
IRQ2 = 34, // slave
IRQ3 = 35, // serial2
IRQ4 = 36, // serial1
IRQ5 = 37, // LPT2
IRQ6 = 38, // floppy
IRQ7 = 39, // LPT1
IRQ8 = 40, // RTC
IRQ9 = 41, // IRQ2
IRQ10 = 42, // reserve
IRQ11 = 43, // reserve
MOUSE = 44, // PS/2 mouse
IRQ13 = 45, // FPU
ATA1 = 46, // ATA HD1
ATA2 = 47, // ATA HD2
}
///8259A chip
pub struct | {
offset: u8,
command: UnsafePort<u8>,
data: UnsafePort<u8>
}
impl Pic8259A {
pub const unsafe fn new(base: u16, offset: u8) -> Pic8259A {
Pic8259A {
offset: offset,
command: UnsafePort::new(base),
data: UnsafePort::new(base+1)
}
}
pub unsafe fn eoi(&mut self) {
self.command.write(0x20);
}
}
/// represent two cascaded pic chips
pub struct PicChain {
pics: [Pic8259A; 2],
irqmask: u16
}
pub static PIC_CHAIN: Mutex<PicChain> = Mutex::new(unsafe {PicChain::new()});
/* reinitialize the PIC controllers, giving them specified vector offsets
rather than 8h and 70h, as configured by default */
const ICW1_ICW4: u8 = 0x01; /* ICW4 (not) needed */
#[allow(dead_code)]
const ICW1_SINGLE: u8 = 0x02; /* Single (cascade) mode */
#[allow(dead_code)]
const ICW1_INTERVAL4: u8 = 0x04; /* Call address interval 4 (8) */
#[allow(dead_code)]
const ICW1_LEVEL: u8 = 0x08; /* Level triggered (edge) mode */
#[allow(dead_code)]
const ICW1_INIT: u8 = 0x10; /* Initialization - required! */
const ICW4_8086: u8 = 0x01; /* 8086/88 (MCS-80/85) mode */
#[allow(dead_code)]
const ICW4_AUTO: u8 = 0x02; /* Auto (normal) EOI */
#[allow(dead_code)]
const ICW4_BUF_SLAVE: u8 = 0x08; /* Buffered mode/slave */
#[allow(dead_code)]
const ICW4_BUF_MASTER: u8 = 0x0C; /* Buffered mode/master */
#[allow(dead_code)]
const ICW4_SFNM: u8 = 0x10; /* Special fully nested (not) */
impl PicChain {
pub const unsafe fn new() -> PicChain {
PicChain {
pics: [
Pic8259A::new(PIC1_BASE, 0x20),
Pic8259A::new(PIC2_BASE, 0x28),
],
irqmask: IRQ_MASK
}
}
pub unsafe fn init(&mut self) {
let mut port80 = Port::new(0x80);
let mut io_wait = || port80.write(0 as u8);
self.pics[0].command.write(ICW1_INIT + ICW1_ICW4);
io_wait();
self.pics[1].command.write(ICW1_INIT + ICW1_ICW4);
io_wait();
self.pics[0].data.write(self.pics[0].offset);
io_wait();
self.pics[1].data.write(self.pics[1].offset);
io_wait();
// ICW3: tell Master PIC that there is a slave PIC at IRQ2
self.pics[0].data.write(0b0000_0100);
io_wait();
// ICW3: tell Slave PIC its cascade identity (0000 0010)
self.pics[1].data.write(0x2);
io_wait();
self.pics[0].data.write(ICW4_8086);
io_wait();
self.pics[1].data.write(ICW4_8086);
io_wait();
let mask =self.irqmask;
self.setmask(mask);
}
pub unsafe fn eoi(&mut self, isr: usize) {
assert!(isr < 0x10);
if isr >= 8 {
self.pics[1].eoi();
}
self.pics[0].eoi();
}
unsafe fn setmask(&mut self, mask: u16) {
self.irqmask = mask;
self.pics[0].data.write(mask as u8);
self.pics[1].data.write((mask >> 8) as u8);
}
pub unsafe fn enable(&mut self, irq: usize) {
assert!(irq >= 0x20 && irq < 0x30);
let irq = (irq - 0x20) as u16;
let mask = self.irqmask &!(1<<irq);
self.setmask(mask);
}
}
| Pic8259A | identifier_name |
table_caption.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! CSS table formatting contexts.
use app_units::Au;
use block::BlockFlow;
use context::LayoutContext;
use display_list::{BlockFlowDisplayListBuilding, DisplayListBuildState};
use display_list::{StackingContextCollectionFlags, StackingContextCollectionState};
use euclid::Point2D;
use flow::{Flow, FlowClass, OpaqueFlow};
use fragment::{Fragment, FragmentBorderBoxIterator, Overflow};
use gfx_traits::print_tree::PrintTree;
use std::fmt;
use style::logical_geometry::LogicalSize;
use style::properties::ComputedValues;
#[allow(unsafe_code)]
unsafe impl ::flow::HasBaseFlow for TableCaptionFlow {}
/// A table formatting context.
#[repr(C)]
pub struct TableCaptionFlow {
pub block_flow: BlockFlow,
}
impl TableCaptionFlow {
pub fn from_fragment(fragment: Fragment) -> TableCaptionFlow {
TableCaptionFlow {
block_flow: BlockFlow::from_fragment(fragment),
}
}
}
impl Flow for TableCaptionFlow {
fn class(&self) -> FlowClass {
FlowClass::TableCaption
}
fn as_mut_table_caption(&mut self) -> &mut TableCaptionFlow {
self
}
fn as_mut_block(&mut self) -> &mut BlockFlow {
&mut self.block_flow
}
fn as_block(&self) -> &BlockFlow {
&self.block_flow
}
fn bubble_inline_sizes(&mut self) {
self.block_flow.bubble_inline_sizes();
}
fn assign_inline_sizes(&mut self, layout_context: &LayoutContext) {
debug!(
"assign_inline_sizes({}): assigning inline_size for flow",
"table_caption"
);
self.block_flow.assign_inline_sizes(layout_context);
}
fn assign_block_size(&mut self, layout_context: &LayoutContext) {
debug!("assign_block_size: assigning block_size for table_caption");
self.block_flow.assign_block_size(layout_context);
}
fn compute_stacking_relative_position(&mut self, layout_context: &LayoutContext) {
self.block_flow
.compute_stacking_relative_position(layout_context)
}
fn update_late_computed_inline_position_if_necessary(&mut self, inline_position: Au) {
self.block_flow
.update_late_computed_inline_position_if_necessary(inline_position)
}
fn update_late_computed_block_position_if_necessary(&mut self, block_position: Au) {
self.block_flow
.update_late_computed_block_position_if_necessary(block_position)
}
fn build_display_list(&mut self, state: &mut DisplayListBuildState) {
debug!("build_display_list_table_caption: same process as block flow");
self.block_flow.build_display_list(state);
}
fn collect_stacking_contexts(&mut self, state: &mut StackingContextCollectionState) {
self.block_flow
.collect_stacking_contexts_for_block(state, StackingContextCollectionFlags::empty());
}
fn repair_style(&mut self, new_style: &::ServoArc<ComputedValues>) |
fn compute_overflow(&self) -> Overflow {
self.block_flow.compute_overflow()
}
fn contains_roots_of_absolute_flow_tree(&self) -> bool {
self.block_flow.contains_roots_of_absolute_flow_tree()
}
fn is_absolute_containing_block(&self) -> bool {
self.block_flow.is_absolute_containing_block()
}
fn generated_containing_block_size(&self, flow: OpaqueFlow) -> LogicalSize<Au> {
self.block_flow.generated_containing_block_size(flow)
}
fn iterate_through_fragment_border_boxes(
&self,
iterator: &mut FragmentBorderBoxIterator,
level: i32,
stacking_context_position: &Point2D<Au>,
) {
self.block_flow.iterate_through_fragment_border_boxes(
iterator,
level,
stacking_context_position,
)
}
fn mutate_fragments(&mut self, mutator: &mut FnMut(&mut Fragment)) {
self.block_flow.mutate_fragments(mutator)
}
fn print_extra_flow_children(&self, print_tree: &mut PrintTree) {
self.block_flow.print_extra_flow_children(print_tree);
}
}
impl fmt::Debug for TableCaptionFlow {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "TableCaptionFlow: {:?}", self.block_flow)
}
}
| {
self.block_flow.repair_style(new_style)
} | identifier_body |
table_caption.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! CSS table formatting contexts.
use app_units::Au;
use block::BlockFlow;
use context::LayoutContext;
use display_list::{BlockFlowDisplayListBuilding, DisplayListBuildState};
use display_list::{StackingContextCollectionFlags, StackingContextCollectionState};
use euclid::Point2D;
use flow::{Flow, FlowClass, OpaqueFlow};
use fragment::{Fragment, FragmentBorderBoxIterator, Overflow};
use gfx_traits::print_tree::PrintTree;
use std::fmt;
use style::logical_geometry::LogicalSize;
use style::properties::ComputedValues;
#[allow(unsafe_code)]
unsafe impl ::flow::HasBaseFlow for TableCaptionFlow {}
/// A table formatting context.
#[repr(C)]
pub struct TableCaptionFlow {
pub block_flow: BlockFlow,
}
impl TableCaptionFlow {
pub fn from_fragment(fragment: Fragment) -> TableCaptionFlow {
TableCaptionFlow {
block_flow: BlockFlow::from_fragment(fragment),
}
}
}
impl Flow for TableCaptionFlow {
fn class(&self) -> FlowClass {
FlowClass::TableCaption
}
fn as_mut_table_caption(&mut self) -> &mut TableCaptionFlow {
self
}
fn as_mut_block(&mut self) -> &mut BlockFlow {
&mut self.block_flow
}
fn as_block(&self) -> &BlockFlow {
&self.block_flow
}
fn bubble_inline_sizes(&mut self) {
self.block_flow.bubble_inline_sizes();
}
fn assign_inline_sizes(&mut self, layout_context: &LayoutContext) {
debug!(
"assign_inline_sizes({}): assigning inline_size for flow",
"table_caption"
);
self.block_flow.assign_inline_sizes(layout_context);
}
fn assign_block_size(&mut self, layout_context: &LayoutContext) {
debug!("assign_block_size: assigning block_size for table_caption");
self.block_flow.assign_block_size(layout_context);
}
fn compute_stacking_relative_position(&mut self, layout_context: &LayoutContext) {
self.block_flow
.compute_stacking_relative_position(layout_context)
}
fn update_late_computed_inline_position_if_necessary(&mut self, inline_position: Au) {
self.block_flow
.update_late_computed_inline_position_if_necessary(inline_position)
}
fn update_late_computed_block_position_if_necessary(&mut self, block_position: Au) {
self.block_flow
.update_late_computed_block_position_if_necessary(block_position)
}
fn build_display_list(&mut self, state: &mut DisplayListBuildState) {
debug!("build_display_list_table_caption: same process as block flow");
self.block_flow.build_display_list(state);
}
fn collect_stacking_contexts(&mut self, state: &mut StackingContextCollectionState) {
self.block_flow
.collect_stacking_contexts_for_block(state, StackingContextCollectionFlags::empty());
}
fn repair_style(&mut self, new_style: &::ServoArc<ComputedValues>) {
self.block_flow.repair_style(new_style)
}
fn compute_overflow(&self) -> Overflow {
self.block_flow.compute_overflow()
}
fn contains_roots_of_absolute_flow_tree(&self) -> bool {
self.block_flow.contains_roots_of_absolute_flow_tree() | }
fn is_absolute_containing_block(&self) -> bool {
self.block_flow.is_absolute_containing_block()
}
fn generated_containing_block_size(&self, flow: OpaqueFlow) -> LogicalSize<Au> {
self.block_flow.generated_containing_block_size(flow)
}
fn iterate_through_fragment_border_boxes(
&self,
iterator: &mut FragmentBorderBoxIterator,
level: i32,
stacking_context_position: &Point2D<Au>,
) {
self.block_flow.iterate_through_fragment_border_boxes(
iterator,
level,
stacking_context_position,
)
}
fn mutate_fragments(&mut self, mutator: &mut FnMut(&mut Fragment)) {
self.block_flow.mutate_fragments(mutator)
}
fn print_extra_flow_children(&self, print_tree: &mut PrintTree) {
self.block_flow.print_extra_flow_children(print_tree);
}
}
impl fmt::Debug for TableCaptionFlow {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "TableCaptionFlow: {:?}", self.block_flow)
}
} | random_line_split | |
table_caption.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! CSS table formatting contexts.
use app_units::Au;
use block::BlockFlow;
use context::LayoutContext;
use display_list::{BlockFlowDisplayListBuilding, DisplayListBuildState};
use display_list::{StackingContextCollectionFlags, StackingContextCollectionState};
use euclid::Point2D;
use flow::{Flow, FlowClass, OpaqueFlow};
use fragment::{Fragment, FragmentBorderBoxIterator, Overflow};
use gfx_traits::print_tree::PrintTree;
use std::fmt;
use style::logical_geometry::LogicalSize;
use style::properties::ComputedValues;
#[allow(unsafe_code)]
unsafe impl ::flow::HasBaseFlow for TableCaptionFlow {}
/// A table formatting context.
#[repr(C)]
pub struct TableCaptionFlow {
pub block_flow: BlockFlow,
}
impl TableCaptionFlow {
pub fn from_fragment(fragment: Fragment) -> TableCaptionFlow {
TableCaptionFlow {
block_flow: BlockFlow::from_fragment(fragment),
}
}
}
impl Flow for TableCaptionFlow {
fn class(&self) -> FlowClass {
FlowClass::TableCaption
}
fn as_mut_table_caption(&mut self) -> &mut TableCaptionFlow {
self
}
fn as_mut_block(&mut self) -> &mut BlockFlow {
&mut self.block_flow
}
fn as_block(&self) -> &BlockFlow {
&self.block_flow
}
fn bubble_inline_sizes(&mut self) {
self.block_flow.bubble_inline_sizes();
}
fn assign_inline_sizes(&mut self, layout_context: &LayoutContext) {
debug!(
"assign_inline_sizes({}): assigning inline_size for flow",
"table_caption"
);
self.block_flow.assign_inline_sizes(layout_context);
}
fn assign_block_size(&mut self, layout_context: &LayoutContext) {
debug!("assign_block_size: assigning block_size for table_caption");
self.block_flow.assign_block_size(layout_context);
}
fn compute_stacking_relative_position(&mut self, layout_context: &LayoutContext) {
self.block_flow
.compute_stacking_relative_position(layout_context)
}
fn update_late_computed_inline_position_if_necessary(&mut self, inline_position: Au) {
self.block_flow
.update_late_computed_inline_position_if_necessary(inline_position)
}
fn update_late_computed_block_position_if_necessary(&mut self, block_position: Au) {
self.block_flow
.update_late_computed_block_position_if_necessary(block_position)
}
fn build_display_list(&mut self, state: &mut DisplayListBuildState) {
debug!("build_display_list_table_caption: same process as block flow");
self.block_flow.build_display_list(state);
}
fn collect_stacking_contexts(&mut self, state: &mut StackingContextCollectionState) {
self.block_flow
.collect_stacking_contexts_for_block(state, StackingContextCollectionFlags::empty());
}
fn repair_style(&mut self, new_style: &::ServoArc<ComputedValues>) {
self.block_flow.repair_style(new_style)
}
fn compute_overflow(&self) -> Overflow {
self.block_flow.compute_overflow()
}
fn contains_roots_of_absolute_flow_tree(&self) -> bool {
self.block_flow.contains_roots_of_absolute_flow_tree()
}
fn is_absolute_containing_block(&self) -> bool {
self.block_flow.is_absolute_containing_block()
}
fn generated_containing_block_size(&self, flow: OpaqueFlow) -> LogicalSize<Au> {
self.block_flow.generated_containing_block_size(flow)
}
fn iterate_through_fragment_border_boxes(
&self,
iterator: &mut FragmentBorderBoxIterator,
level: i32,
stacking_context_position: &Point2D<Au>,
) {
self.block_flow.iterate_through_fragment_border_boxes(
iterator,
level,
stacking_context_position,
)
}
fn mutate_fragments(&mut self, mutator: &mut FnMut(&mut Fragment)) {
self.block_flow.mutate_fragments(mutator)
}
fn | (&self, print_tree: &mut PrintTree) {
self.block_flow.print_extra_flow_children(print_tree);
}
}
impl fmt::Debug for TableCaptionFlow {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "TableCaptionFlow: {:?}", self.block_flow)
}
}
| print_extra_flow_children | identifier_name |
coherence-overlap-downstream.rs | // 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.
// Tests that we consider `T: Sugar + Fruit` to be ambiguous, even
// though no impls are found.
pub trait Sugar {}
pub trait Fruit {}
pub trait Sweet {}
impl<T:Sugar> Sweet for T { }
impl<T:Fruit> Sweet for T { }
//~^ ERROR E0119
pub trait Foo<X> {}
pub trait Bar<X> {}
impl<X, T> Foo<X> for T where T: Bar<X> {}
impl<X> Foo<X> for i32 {}
//~^ ERROR E0119
fn main() | { } | identifier_body | |
coherence-overlap-downstream.rs | // 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.
// Tests that we consider `T: Sugar + Fruit` to be ambiguous, even
// though no impls are found.
pub trait Sugar {}
pub trait Fruit {}
pub trait Sweet {}
impl<T:Sugar> Sweet for T { }
impl<T:Fruit> Sweet for T { }
//~^ ERROR E0119
pub trait Foo<X> {}
pub trait Bar<X> {}
impl<X, T> Foo<X> for T where T: Bar<X> {}
impl<X> Foo<X> for i32 {}
//~^ ERROR E0119
fn | () { }
| main | identifier_name |
coherence-overlap-downstream.rs | // 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.
// Tests that we consider `T: Sugar + Fruit` to be ambiguous, even |
pub trait Sugar {}
pub trait Fruit {}
pub trait Sweet {}
impl<T:Sugar> Sweet for T { }
impl<T:Fruit> Sweet for T { }
//~^ ERROR E0119
pub trait Foo<X> {}
pub trait Bar<X> {}
impl<X, T> Foo<X> for T where T: Bar<X> {}
impl<X> Foo<X> for i32 {}
//~^ ERROR E0119
fn main() { } | // though no impls are found. | random_line_split |
lib.rs | // 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.
//! Lints in the Rust compiler.
//!
//! This currently only contains the definitions and implementations
//! of most of the lints that `rustc` supports directly, it does not
//! contain the infrastructure for defining/registering lints. That is
//! available in `rustc::lint` and `rustc::plugin` respectively.
//!
//! # Note
//!
//! This API is completely unstable and subject to change.
// Do not remove on snapshot creation. Needed for bootstrap. (Issue #22364)
#![cfg_attr(stage0, feature(custom_attribute))]
#![crate_name = "rustc_lint"]
#![unstable(feature = "rustc_private")]
#![staged_api]
#![crate_type = "dylib"]
#![crate_type = "rlib"]
#![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
html_root_url = "http://doc.rust-lang.org/nightly/")]
#![feature(box_patterns)]
#![feature(box_syntax)]
#![feature(collections)]
#![feature(core)]
#![feature(quote)]
#![feature(rustc_diagnostic_macros)]
#![feature(rustc_private)]
#![feature(staged_api)]
#![feature(str_char)]
#![cfg_attr(test, feature(test))]
extern crate syntax;
#[macro_use]
extern crate rustc;
#[macro_use]
extern crate log;
pub use rustc::lint as lint;
pub use rustc::metadata as metadata;
pub use rustc::middle as middle;
pub use rustc::session as session;
pub use rustc::util as util;
use session::Session;
use lint::LintId;
mod builtin;
/// Tell the `LintStore` about all the built-in lints (the ones
/// defined in this crate and the ones defined in
/// `rustc::lint::builtin`).
pub fn register_builtins(store: &mut lint::LintStore, sess: Option<&Session>) | )
}
add_builtin!(sess,
HardwiredLints,
WhileTrue,
ImproperCTypes,
BoxPointers,
UnusedAttributes,
PathStatements,
UnusedResults,
NonCamelCaseTypes,
NonSnakeCase,
NonUpperCaseGlobals,
UnusedParens,
UnusedImportBraces,
NonShorthandFieldPatterns,
UnusedUnsafe,
UnsafeCode,
UnusedMut,
UnusedAllocation,
MissingCopyImplementations,
UnstableFeatures,
Stability,
UnconditionalRecursion,
InvalidNoMangleItems,
PluginAsLibrary,
DropWithReprExtern,
MutableTransmutes,
);
add_builtin_with_new!(sess,
TypeLimits,
RawPointerDerive,
MissingDoc,
MissingDebugImplementations,
);
add_lint_group!(sess, "bad_style",
NON_CAMEL_CASE_TYPES, NON_SNAKE_CASE, NON_UPPER_CASE_GLOBALS);
add_lint_group!(sess, "unused",
UNUSED_IMPORTS, UNUSED_VARIABLES, UNUSED_ASSIGNMENTS, DEAD_CODE,
UNUSED_MUT, UNREACHABLE_CODE, UNUSED_MUST_USE,
UNUSED_UNSAFE, PATH_STATEMENTS);
// We have one lint pass defined specially
store.register_pass(sess, false, box lint::GatherNodeLevels);
// Insert temporary renamings for a one-time deprecation
store.register_renamed("raw_pointer_deriving", "raw_pointer_derive");
store.register_renamed("unknown_features", "unused_features");
}
| {
macro_rules! add_builtin {
($sess:ident, $($name:ident),*,) => (
{$(
store.register_pass($sess, false, box builtin::$name);
)*}
)
}
macro_rules! add_builtin_with_new {
($sess:ident, $($name:ident),*,) => (
{$(
store.register_pass($sess, false, box builtin::$name::new());
)*}
)
}
macro_rules! add_lint_group {
($sess:ident, $name:expr, $($lint:ident),*) => (
store.register_group($sess, false, $name, vec![$(LintId::of(builtin::$lint)),*]); | identifier_body |
lib.rs | // 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.
//! Lints in the Rust compiler.
//!
//! This currently only contains the definitions and implementations
//! of most of the lints that `rustc` supports directly, it does not
//! contain the infrastructure for defining/registering lints. That is
//! available in `rustc::lint` and `rustc::plugin` respectively.
//!
//! # Note
//!
//! This API is completely unstable and subject to change.
// Do not remove on snapshot creation. Needed for bootstrap. (Issue #22364)
#![cfg_attr(stage0, feature(custom_attribute))]
#![crate_name = "rustc_lint"]
#![unstable(feature = "rustc_private")]
#![staged_api]
#![crate_type = "dylib"]
#![crate_type = "rlib"]
#![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
html_root_url = "http://doc.rust-lang.org/nightly/")]
#![feature(box_patterns)]
#![feature(box_syntax)]
#![feature(collections)]
#![feature(core)]
#![feature(quote)]
#![feature(rustc_diagnostic_macros)]
#![feature(rustc_private)]
#![feature(staged_api)]
#![feature(str_char)]
#![cfg_attr(test, feature(test))]
extern crate syntax;
#[macro_use]
extern crate rustc;
#[macro_use]
extern crate log;
pub use rustc::lint as lint;
pub use rustc::metadata as metadata;
pub use rustc::middle as middle;
pub use rustc::session as session;
pub use rustc::util as util;
use session::Session;
use lint::LintId;
mod builtin;
/// Tell the `LintStore` about all the built-in lints (the ones
/// defined in this crate and the ones defined in
/// `rustc::lint::builtin`).
pub fn | (store: &mut lint::LintStore, sess: Option<&Session>) {
macro_rules! add_builtin {
($sess:ident, $($name:ident),*,) => (
{$(
store.register_pass($sess, false, box builtin::$name);
)*}
)
}
macro_rules! add_builtin_with_new {
($sess:ident, $($name:ident),*,) => (
{$(
store.register_pass($sess, false, box builtin::$name::new());
)*}
)
}
macro_rules! add_lint_group {
($sess:ident, $name:expr, $($lint:ident),*) => (
store.register_group($sess, false, $name, vec![$(LintId::of(builtin::$lint)),*]);
)
}
add_builtin!(sess,
HardwiredLints,
WhileTrue,
ImproperCTypes,
BoxPointers,
UnusedAttributes,
PathStatements,
UnusedResults,
NonCamelCaseTypes,
NonSnakeCase,
NonUpperCaseGlobals,
UnusedParens,
UnusedImportBraces,
NonShorthandFieldPatterns,
UnusedUnsafe,
UnsafeCode,
UnusedMut,
UnusedAllocation,
MissingCopyImplementations,
UnstableFeatures,
Stability,
UnconditionalRecursion,
InvalidNoMangleItems,
PluginAsLibrary,
DropWithReprExtern,
MutableTransmutes,
);
add_builtin_with_new!(sess,
TypeLimits,
RawPointerDerive,
MissingDoc,
MissingDebugImplementations,
);
add_lint_group!(sess, "bad_style",
NON_CAMEL_CASE_TYPES, NON_SNAKE_CASE, NON_UPPER_CASE_GLOBALS);
add_lint_group!(sess, "unused",
UNUSED_IMPORTS, UNUSED_VARIABLES, UNUSED_ASSIGNMENTS, DEAD_CODE,
UNUSED_MUT, UNREACHABLE_CODE, UNUSED_MUST_USE,
UNUSED_UNSAFE, PATH_STATEMENTS);
// We have one lint pass defined specially
store.register_pass(sess, false, box lint::GatherNodeLevels);
// Insert temporary renamings for a one-time deprecation
store.register_renamed("raw_pointer_deriving", "raw_pointer_derive");
store.register_renamed("unknown_features", "unused_features");
}
| register_builtins | identifier_name |
lib.rs | // 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.
//! Lints in the Rust compiler.
//!
//! This currently only contains the definitions and implementations
//! of most of the lints that `rustc` supports directly, it does not
//! contain the infrastructure for defining/registering lints. That is
//! available in `rustc::lint` and `rustc::plugin` respectively.
//!
//! # Note
//!
//! This API is completely unstable and subject to change.
// Do not remove on snapshot creation. Needed for bootstrap. (Issue #22364)
#![cfg_attr(stage0, feature(custom_attribute))]
#![crate_name = "rustc_lint"]
#![unstable(feature = "rustc_private")]
#![staged_api]
#![crate_type = "dylib"]
#![crate_type = "rlib"]
#![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
html_root_url = "http://doc.rust-lang.org/nightly/")]
#![feature(box_patterns)]
#![feature(box_syntax)]
#![feature(collections)]
#![feature(core)]
#![feature(quote)]
#![feature(rustc_diagnostic_macros)]
#![feature(rustc_private)]
#![feature(staged_api)]
#![feature(str_char)]
#![cfg_attr(test, feature(test))]
extern crate syntax;
#[macro_use]
extern crate rustc;
#[macro_use]
extern crate log;
pub use rustc::lint as lint;
pub use rustc::metadata as metadata;
pub use rustc::middle as middle;
pub use rustc::session as session;
pub use rustc::util as util;
use session::Session;
use lint::LintId;
mod builtin;
/// Tell the `LintStore` about all the built-in lints (the ones
/// defined in this crate and the ones defined in
/// `rustc::lint::builtin`).
pub fn register_builtins(store: &mut lint::LintStore, sess: Option<&Session>) {
macro_rules! add_builtin {
($sess:ident, $($name:ident),*,) => (
{$(
store.register_pass($sess, false, box builtin::$name);
)*}
)
}
macro_rules! add_builtin_with_new {
($sess:ident, $($name:ident),*,) => (
{$(
store.register_pass($sess, false, box builtin::$name::new());
)*}
)
}
macro_rules! add_lint_group { |
add_builtin!(sess,
HardwiredLints,
WhileTrue,
ImproperCTypes,
BoxPointers,
UnusedAttributes,
PathStatements,
UnusedResults,
NonCamelCaseTypes,
NonSnakeCase,
NonUpperCaseGlobals,
UnusedParens,
UnusedImportBraces,
NonShorthandFieldPatterns,
UnusedUnsafe,
UnsafeCode,
UnusedMut,
UnusedAllocation,
MissingCopyImplementations,
UnstableFeatures,
Stability,
UnconditionalRecursion,
InvalidNoMangleItems,
PluginAsLibrary,
DropWithReprExtern,
MutableTransmutes,
);
add_builtin_with_new!(sess,
TypeLimits,
RawPointerDerive,
MissingDoc,
MissingDebugImplementations,
);
add_lint_group!(sess, "bad_style",
NON_CAMEL_CASE_TYPES, NON_SNAKE_CASE, NON_UPPER_CASE_GLOBALS);
add_lint_group!(sess, "unused",
UNUSED_IMPORTS, UNUSED_VARIABLES, UNUSED_ASSIGNMENTS, DEAD_CODE,
UNUSED_MUT, UNREACHABLE_CODE, UNUSED_MUST_USE,
UNUSED_UNSAFE, PATH_STATEMENTS);
// We have one lint pass defined specially
store.register_pass(sess, false, box lint::GatherNodeLevels);
// Insert temporary renamings for a one-time deprecation
store.register_renamed("raw_pointer_deriving", "raw_pointer_derive");
store.register_renamed("unknown_features", "unused_features");
} | ($sess:ident, $name:expr, $($lint:ident),*) => (
store.register_group($sess, false, $name, vec![$(LintId::of(builtin::$lint)),*]);
)
} | random_line_split |
multiple_files.rs | // 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.
#![feature(rand)]
use std::fs::File;
use std::io::prelude::*;
use std::path::Path;
use std::process::Command;
use std::__rand::{thread_rng, Rng};
use std::{char, env};
// creates unicode_input_multiple_files_{main,chars}.rs, where the
// former imports the latter. `_chars` just contains an identifier
// made up of random characters, because will emit an error message
// about the ident being in the wrong place, with a span (and creating
// this span used to upset the compiler).
fn random_char() -> char |
fn main() {
let args: Vec<String> = env::args().collect();
let rustc = &args[1];
let tmpdir = Path::new(&args[2]);
let main_file = tmpdir.join("unicode_input_multiple_files_main.rs");
{
let _ = File::create(&main_file).unwrap()
.write_all(b"mod unicode_input_multiple_files_chars;").unwrap();
}
for _ in 0..100 {
{
let randoms = tmpdir.join("unicode_input_multiple_files_chars.rs");
let mut w = File::create(&randoms).unwrap();
for _ in 0..30 {
write!(&mut w, "{}", random_char()).unwrap();
}
}
// rustc is passed to us with --out-dir and -L etc., so we
// can't exec it directly
let result = Command::new("sh")
.arg("-c")
.arg(&format!("{} {}",
rustc,
main_file.display()))
.output().unwrap();
let err = String::from_utf8_lossy(&result.stderr);
// positive test so that this test will be updated when the
// compiler changes.
assert!(err.contains("expected item, found"))
}
}
| {
let mut rng = thread_rng();
// a subset of the XID_start Unicode table (ensuring that the
// compiler doesn't fail with an "unrecognised token" error)
let (lo, hi): (u32, u32) = match rng.gen_range(1u32, 4u32 + 1) {
1 => (0x41, 0x5a),
2 => (0xf8, 0x1ba),
3 => (0x1401, 0x166c),
_ => (0x10400, 0x1044f)
};
char::from_u32(rng.gen_range(lo, hi + 1)).unwrap()
} | identifier_body |
multiple_files.rs | // 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.
#![feature(rand)]
use std::fs::File;
use std::io::prelude::*;
use std::path::Path;
use std::process::Command;
use std::__rand::{thread_rng, Rng};
use std::{char, env};
// creates unicode_input_multiple_files_{main,chars}.rs, where the
// former imports the latter. `_chars` just contains an identifier
// made up of random characters, because will emit an error message
// about the ident being in the wrong place, with a span (and creating
// this span used to upset the compiler).
fn random_char() -> char {
let mut rng = thread_rng();
// a subset of the XID_start Unicode table (ensuring that the
// compiler doesn't fail with an "unrecognised token" error)
let (lo, hi): (u32, u32) = match rng.gen_range(1u32, 4u32 + 1) {
1 => (0x41, 0x5a),
2 => (0xf8, 0x1ba),
3 => (0x1401, 0x166c),
_ => (0x10400, 0x1044f)
};
char::from_u32(rng.gen_range(lo, hi + 1)).unwrap() | let rustc = &args[1];
let tmpdir = Path::new(&args[2]);
let main_file = tmpdir.join("unicode_input_multiple_files_main.rs");
{
let _ = File::create(&main_file).unwrap()
.write_all(b"mod unicode_input_multiple_files_chars;").unwrap();
}
for _ in 0..100 {
{
let randoms = tmpdir.join("unicode_input_multiple_files_chars.rs");
let mut w = File::create(&randoms).unwrap();
for _ in 0..30 {
write!(&mut w, "{}", random_char()).unwrap();
}
}
// rustc is passed to us with --out-dir and -L etc., so we
// can't exec it directly
let result = Command::new("sh")
.arg("-c")
.arg(&format!("{} {}",
rustc,
main_file.display()))
.output().unwrap();
let err = String::from_utf8_lossy(&result.stderr);
// positive test so that this test will be updated when the
// compiler changes.
assert!(err.contains("expected item, found"))
}
} | }
fn main() {
let args: Vec<String> = env::args().collect(); | random_line_split |
multiple_files.rs | // 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.
#![feature(rand)]
use std::fs::File;
use std::io::prelude::*;
use std::path::Path;
use std::process::Command;
use std::__rand::{thread_rng, Rng};
use std::{char, env};
// creates unicode_input_multiple_files_{main,chars}.rs, where the
// former imports the latter. `_chars` just contains an identifier
// made up of random characters, because will emit an error message
// about the ident being in the wrong place, with a span (and creating
// this span used to upset the compiler).
fn random_char() -> char {
let mut rng = thread_rng();
// a subset of the XID_start Unicode table (ensuring that the
// compiler doesn't fail with an "unrecognised token" error)
let (lo, hi): (u32, u32) = match rng.gen_range(1u32, 4u32 + 1) {
1 => (0x41, 0x5a),
2 => (0xf8, 0x1ba),
3 => (0x1401, 0x166c),
_ => (0x10400, 0x1044f)
};
char::from_u32(rng.gen_range(lo, hi + 1)).unwrap()
}
fn | () {
let args: Vec<String> = env::args().collect();
let rustc = &args[1];
let tmpdir = Path::new(&args[2]);
let main_file = tmpdir.join("unicode_input_multiple_files_main.rs");
{
let _ = File::create(&main_file).unwrap()
.write_all(b"mod unicode_input_multiple_files_chars;").unwrap();
}
for _ in 0..100 {
{
let randoms = tmpdir.join("unicode_input_multiple_files_chars.rs");
let mut w = File::create(&randoms).unwrap();
for _ in 0..30 {
write!(&mut w, "{}", random_char()).unwrap();
}
}
// rustc is passed to us with --out-dir and -L etc., so we
// can't exec it directly
let result = Command::new("sh")
.arg("-c")
.arg(&format!("{} {}",
rustc,
main_file.display()))
.output().unwrap();
let err = String::from_utf8_lossy(&result.stderr);
// positive test so that this test will be updated when the
// compiler changes.
assert!(err.contains("expected item, found"))
}
}
| main | identifier_name |
traffic.rs | use std::env;
use tokio::runtime::Runtime;
use hubcaps::traffic::TimeUnit;
use hubcaps::{Credentials, Github, Result};
fn | () -> Result<()> {
pretty_env_logger::init();
match env::var("GITHUB_TOKEN").ok() {
Some(token) => {
let mut rt = Runtime::new()?;
let github = Github::new(
concat!(env!("CARGO_PKG_NAME"), "/", env!("CARGO_PKG_VERSION")),
Credentials::Token(token),
)?;
let owner = "softprops";
let repo = "hubcaps";
println!("Top 10 referrers");
for referrer in rt.block_on(github.repo(owner, repo).traffic().referrers())? {
println!("{:#?}", referrer)
}
println!("Top 10 paths");
for path in rt.block_on(github.repo(owner, repo).traffic().paths())? {
println!("{:#?}", path)
}
println!("Views per day");
let views = rt.block_on(github.repo(owner, repo).traffic().views(TimeUnit::Day))?;
println!("{:#?}", views);
println!("Clones per day");
let clones = rt.block_on(github.repo(owner, repo).traffic().clones(TimeUnit::Day))?;
println!("{:#?}", clones);
Ok(())
}
_ => Err("example missing GITHUB_TOKEN".into()),
}
}
| main | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.