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 |
---|---|---|---|---|
tree.rs
|
#![cfg_attr(feature = "unstable", feature(test))]
extern crate rand;
extern crate rdxsort;
#[cfg(feature = "unstable")]
mod unstable {
extern crate test;
use self::test::Bencher;
use rand::{Rng, XorShiftRng};
use rdxsort::*;
use std::collections::BTreeSet;
use std::collections::HashSet;
static N_MEDIUM: usize = 10_000;
fn bench_generic<F>(b: &mut Bencher, f: F) where F: Fn(Vec<u32>) {
let mut set = HashSet::new();
let mut rng = XorShiftRng::new_unseeded();
while set.len() < N_MEDIUM {
set.insert(rng.gen::<u32>());
}
let mut vec: Vec<u32> = set.into_iter().collect();
rng.shuffle(&mut vec[..]);
let _ = b.iter(|| {
let vec = vec.clone();
f(vec);
});
}
#[bench]
fn bench_set_rdx(b: &mut Bencher) {
bench_generic(b, |vec| {
let mut set = RdxTree::new();
for x in vec {
set.insert(x);
}
});
|
#[bench]
fn bench_set_std(b: &mut Bencher) {
bench_generic(b, |vec| {
let mut set = BTreeSet::new();
for x in vec {
set.insert(x);
}
});
}
}
|
}
|
random_line_split
|
build.rs
|
use std::env;
use std::path::PathBuf;
fn main() {
let target = env::var("TARGET").unwrap();
if target.contains("pc-windows") {
let manifest_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap());
let mut lib_dir = manifest_dir.clone();
let mut dll_dir = manifest_dir.clone();
if target.contains("msvc")
|
else {
lib_dir.push("gnu-mingw");
dll_dir.push("gnu-mingw");
}
lib_dir.push("lib");
dll_dir.push("dll");
if target.contains("x86_64") {
lib_dir.push("64");
dll_dir.push("64");
}
else {
lib_dir.push("32");
dll_dir.push("32");
}
println!("cargo:rustc-link-search=all={}", lib_dir.display());
for entry in std::fs::read_dir(dll_dir).expect("Can't read DLL dir") {
let entry_path = entry.expect("Invalid fs entry").path();
let file_name_result = entry_path.file_name();
let mut new_file_path = manifest_dir.clone();
if let Some(file_name) = file_name_result {
let file_name = file_name.to_str().unwrap();
if file_name.ends_with(".dll") {
new_file_path.push(file_name);
std::fs::copy(&entry_path, new_file_path.as_path()).expect("Can't copy from DLL dir");
}
}
}
}
}
|
{
lib_dir.push("msvc");
dll_dir.push("msvc");
}
|
conditional_block
|
build.rs
|
use std::env;
use std::path::PathBuf;
fn main()
|
else {
lib_dir.push("32");
dll_dir.push("32");
}
println!("cargo:rustc-link-search=all={}", lib_dir.display());
for entry in std::fs::read_dir(dll_dir).expect("Can't read DLL dir") {
let entry_path = entry.expect("Invalid fs entry").path();
let file_name_result = entry_path.file_name();
let mut new_file_path = manifest_dir.clone();
if let Some(file_name) = file_name_result {
let file_name = file_name.to_str().unwrap();
if file_name.ends_with(".dll") {
new_file_path.push(file_name);
std::fs::copy(&entry_path, new_file_path.as_path()).expect("Can't copy from DLL dir");
}
}
}
}
}
|
{
let target = env::var("TARGET").unwrap();
if target.contains("pc-windows") {
let manifest_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap());
let mut lib_dir = manifest_dir.clone();
let mut dll_dir = manifest_dir.clone();
if target.contains("msvc") {
lib_dir.push("msvc");
dll_dir.push("msvc");
}
else {
lib_dir.push("gnu-mingw");
dll_dir.push("gnu-mingw");
}
lib_dir.push("lib");
dll_dir.push("dll");
if target.contains("x86_64") {
lib_dir.push("64");
dll_dir.push("64");
}
|
identifier_body
|
build.rs
|
use std::env;
use std::path::PathBuf;
fn main() {
let target = env::var("TARGET").unwrap();
if target.contains("pc-windows") {
let manifest_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap());
let mut lib_dir = manifest_dir.clone();
let mut dll_dir = manifest_dir.clone();
if target.contains("msvc") {
lib_dir.push("msvc");
dll_dir.push("msvc");
}
else {
lib_dir.push("gnu-mingw");
dll_dir.push("gnu-mingw");
}
lib_dir.push("lib");
dll_dir.push("dll");
if target.contains("x86_64") {
lib_dir.push("64");
dll_dir.push("64");
}
else {
|
let entry_path = entry.expect("Invalid fs entry").path();
let file_name_result = entry_path.file_name();
let mut new_file_path = manifest_dir.clone();
if let Some(file_name) = file_name_result {
let file_name = file_name.to_str().unwrap();
if file_name.ends_with(".dll") {
new_file_path.push(file_name);
std::fs::copy(&entry_path, new_file_path.as_path()).expect("Can't copy from DLL dir");
}
}
}
}
}
|
lib_dir.push("32");
dll_dir.push("32");
}
println!("cargo:rustc-link-search=all={}", lib_dir.display());
for entry in std::fs::read_dir(dll_dir).expect("Can't read DLL dir") {
|
random_line_split
|
build.rs
|
use std::env;
use std::path::PathBuf;
fn
|
() {
let target = env::var("TARGET").unwrap();
if target.contains("pc-windows") {
let manifest_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap());
let mut lib_dir = manifest_dir.clone();
let mut dll_dir = manifest_dir.clone();
if target.contains("msvc") {
lib_dir.push("msvc");
dll_dir.push("msvc");
}
else {
lib_dir.push("gnu-mingw");
dll_dir.push("gnu-mingw");
}
lib_dir.push("lib");
dll_dir.push("dll");
if target.contains("x86_64") {
lib_dir.push("64");
dll_dir.push("64");
}
else {
lib_dir.push("32");
dll_dir.push("32");
}
println!("cargo:rustc-link-search=all={}", lib_dir.display());
for entry in std::fs::read_dir(dll_dir).expect("Can't read DLL dir") {
let entry_path = entry.expect("Invalid fs entry").path();
let file_name_result = entry_path.file_name();
let mut new_file_path = manifest_dir.clone();
if let Some(file_name) = file_name_result {
let file_name = file_name.to_str().unwrap();
if file_name.ends_with(".dll") {
new_file_path.push(file_name);
std::fs::copy(&entry_path, new_file_path.as_path()).expect("Can't copy from DLL dir");
}
}
}
}
}
|
main
|
identifier_name
|
coerce-overloaded-autoderef-fail.rs
|
fn borrow_mut<T>(x: &mut T) -> &mut T { x }
fn borrow<T>(x: &T) -> &T { x }
fn borrow_mut2<T>(_: &mut T, _: &mut T) {}
fn borrow2<T>(_: &mut T, _: &T) {}
fn double_mut_borrow<T>(x: &mut Box<T>) {
let y = borrow_mut(x);
let z = borrow_mut(x);
//~^ ERROR cannot borrow `*x` as mutable more than once at a time
drop((y, z));
}
fn
|
(x: &mut Box<i32>) {
let y = borrow(x);
let z = borrow(x);
**x += 1;
//~^ ERROR cannot assign to `**x` because it is borrowed
drop((y, z));
}
fn double_mut_borrow2<T>(x: &mut Box<T>) {
borrow_mut2(x, x);
//~^ ERROR cannot borrow `*x` as mutable more than once at a time
}
fn double_borrow2<T>(x: &mut Box<T>) {
borrow2(x, x);
//~^ ERROR cannot borrow `*x` as mutable because it is also borrowed as immutable
}
pub fn main() {}
|
double_imm_borrow
|
identifier_name
|
coerce-overloaded-autoderef-fail.rs
|
fn borrow_mut<T>(x: &mut T) -> &mut T { x }
fn borrow<T>(x: &T) -> &T { x }
fn borrow_mut2<T>(_: &mut T, _: &mut T) {}
fn borrow2<T>(_: &mut T, _: &T) {}
fn double_mut_borrow<T>(x: &mut Box<T>) {
let y = borrow_mut(x);
let z = borrow_mut(x);
//~^ ERROR cannot borrow `*x` as mutable more than once at a time
drop((y, z));
}
fn double_imm_borrow(x: &mut Box<i32>) {
let y = borrow(x);
let z = borrow(x);
**x += 1;
//~^ ERROR cannot assign to `**x` because it is borrowed
|
borrow_mut2(x, x);
//~^ ERROR cannot borrow `*x` as mutable more than once at a time
}
fn double_borrow2<T>(x: &mut Box<T>) {
borrow2(x, x);
//~^ ERROR cannot borrow `*x` as mutable because it is also borrowed as immutable
}
pub fn main() {}
|
drop((y, z));
}
fn double_mut_borrow2<T>(x: &mut Box<T>) {
|
random_line_split
|
coerce-overloaded-autoderef-fail.rs
|
fn borrow_mut<T>(x: &mut T) -> &mut T { x }
fn borrow<T>(x: &T) -> &T { x }
fn borrow_mut2<T>(_: &mut T, _: &mut T) {}
fn borrow2<T>(_: &mut T, _: &T) {}
fn double_mut_borrow<T>(x: &mut Box<T>)
|
fn double_imm_borrow(x: &mut Box<i32>) {
let y = borrow(x);
let z = borrow(x);
**x += 1;
//~^ ERROR cannot assign to `**x` because it is borrowed
drop((y, z));
}
fn double_mut_borrow2<T>(x: &mut Box<T>) {
borrow_mut2(x, x);
//~^ ERROR cannot borrow `*x` as mutable more than once at a time
}
fn double_borrow2<T>(x: &mut Box<T>) {
borrow2(x, x);
//~^ ERROR cannot borrow `*x` as mutable because it is also borrowed as immutable
}
pub fn main() {}
|
{
let y = borrow_mut(x);
let z = borrow_mut(x);
//~^ ERROR cannot borrow `*x` as mutable more than once at a time
drop((y, z));
}
|
identifier_body
|
lib.rs
|
// Copyright 2018 Google LLC
//
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file or at
// https://opensource.org/licenses/MIT.
//! Cryptography in Rust.
//!
//! Mundane is a Rust cryptography library backed by BoringSSL that is difficult
//! to misuse, ergonomic, and performant (in that order).
//!
//! # Features
//!
//! By default, Mundane provides only high-level cryptographic primitives.
//! Unless you are implementing cryptographic protocols, these high-level
//! primitives should be all you need. However, if you are sure that you need
//! something lower level, Mundane provides features to enable a number of
//! different low level primitives.
//!
//! WARNING: Being low level, these primitives provide the programmer with more
//! degrees of freedom. There are more conditions that the programmer must meet
//! in order to guarantee security, and thus more ways for the programmer to
//! shoot themself in the foot. Please only use these primitives if you're aware
//! of the risks and are comfortable with the responsibility of using them
//! correctly!
//!
//! **Features**
//!
//! | Name | Description |
//! | -------------- | ------------------------------------|
//! | `kdf` | Key derivation functions |
//! | `bytes` | Low-level operations on byte slices |
//! | `rsa-pkcs1v15` | RSA-PKCS1v1.5 signatures |
//!
//! # Insecure Operations
//!
//! Mundane supports one additional feature not listed in the previous section:
//! `insecure`. This enables some cryptographic primitives which are today
//! considered insecure. These should only be used for compatibility with legacy
//! systems - never in new systems! When the `insecure` feature is used, an
//! `insecure` module is added to the crate root. All insecure primitives are
//! exposed through this module.
#![deny(missing_docs)]
#![deny(warnings)]
// just in case we forget to add #[forbid(unsafe_code)] on new module
// definitions
#![deny(unsafe_code)]
#[macro_use]
mod macros;
// Forbid unsafe code except in the boringssl module.
#[allow(unsafe_code)]
mod boringssl;
#[cfg(any(doc, feature = "bytes"))]
#[forbid(unsafe_code)]
pub mod bytes;
#[forbid(unsafe_code)]
pub mod hash;
#[forbid(unsafe_code)]
pub mod hmac;
#[cfg(any(doc, feature = "insecure"))]
#[forbid(unsafe_code)]
pub mod insecure;
#[cfg(any(doc, feature = "kdf"))]
#[forbid(unsafe_code)]
pub mod kdf;
#[forbid(unsafe_code)]
pub mod password;
#[forbid(unsafe_code)]
pub mod public;
#[forbid(unsafe_code)]
mod util;
|
use boringssl::BoringError;
/// Errors generated by this crate.
///
/// `Error` represents two types of errors: errors generated by BoringSSL, and
/// errors generated by the Rust code in this crate. When printed (using either
/// `Display` or `Debug`), BoringSSL errors are of the form `boringssl:
/// <error>`, while errors generated by Rust code are of the form `<error>`.
pub struct Error(ErrorInner);
impl Error {
fn new(s: String) -> Error {
Error(ErrorInner::Mundane(s))
}
}
#[doc(hidden)]
impl From<BoringError> for Error {
fn from(err: BoringError) -> Error {
Error(ErrorInner::Boring(err))
}
}
impl Display for Error {
fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
match &self.0 {
ErrorInner::Mundane(err) => write!(f, "{}", err),
ErrorInner::Boring(err) => write!(f, "boringssl: {}", err),
}
}
}
impl Debug for Error {
fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
match &self.0 {
ErrorInner::Mundane(err) => write!(f, "{}", err),
ErrorInner::Boring(err) => {
if err.stack_depth() == 1 {
// Either there was no stack trace, or the stack trace only
// contained a single frame. In either case, don't bother
// printing a preceding newline.
write!(f, "boringssl: {:?}", err)
} else {
// There's a multi-line stack trace, so print a preceding
// newline.
write!(f, "boringssl:\n{:?}", err)
}
}
}
}
}
impl std::error::Error for Error {}
enum ErrorInner {
Mundane(String),
Boring(BoringError),
}
#[cfg(test)]
mod tests {
use super::Error;
#[test]
fn test_send() {
fn assert_send<T: Send>() {}
assert_send::<Error>();
}
#[test]
fn test_sync() {
fn assert_sync<T: Sync>() {}
assert_sync::<Error>();
}
}
|
use std::fmt::{self, Debug, Display, Formatter};
|
random_line_split
|
lib.rs
|
// Copyright 2018 Google LLC
//
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file or at
// https://opensource.org/licenses/MIT.
//! Cryptography in Rust.
//!
//! Mundane is a Rust cryptography library backed by BoringSSL that is difficult
//! to misuse, ergonomic, and performant (in that order).
//!
//! # Features
//!
//! By default, Mundane provides only high-level cryptographic primitives.
//! Unless you are implementing cryptographic protocols, these high-level
//! primitives should be all you need. However, if you are sure that you need
//! something lower level, Mundane provides features to enable a number of
//! different low level primitives.
//!
//! WARNING: Being low level, these primitives provide the programmer with more
//! degrees of freedom. There are more conditions that the programmer must meet
//! in order to guarantee security, and thus more ways for the programmer to
//! shoot themself in the foot. Please only use these primitives if you're aware
//! of the risks and are comfortable with the responsibility of using them
//! correctly!
//!
//! **Features**
//!
//! | Name | Description |
//! | -------------- | ------------------------------------|
//! | `kdf` | Key derivation functions |
//! | `bytes` | Low-level operations on byte slices |
//! | `rsa-pkcs1v15` | RSA-PKCS1v1.5 signatures |
//!
//! # Insecure Operations
//!
//! Mundane supports one additional feature not listed in the previous section:
//! `insecure`. This enables some cryptographic primitives which are today
//! considered insecure. These should only be used for compatibility with legacy
//! systems - never in new systems! When the `insecure` feature is used, an
//! `insecure` module is added to the crate root. All insecure primitives are
//! exposed through this module.
#![deny(missing_docs)]
#![deny(warnings)]
// just in case we forget to add #[forbid(unsafe_code)] on new module
// definitions
#![deny(unsafe_code)]
#[macro_use]
mod macros;
// Forbid unsafe code except in the boringssl module.
#[allow(unsafe_code)]
mod boringssl;
#[cfg(any(doc, feature = "bytes"))]
#[forbid(unsafe_code)]
pub mod bytes;
#[forbid(unsafe_code)]
pub mod hash;
#[forbid(unsafe_code)]
pub mod hmac;
#[cfg(any(doc, feature = "insecure"))]
#[forbid(unsafe_code)]
pub mod insecure;
#[cfg(any(doc, feature = "kdf"))]
#[forbid(unsafe_code)]
pub mod kdf;
#[forbid(unsafe_code)]
pub mod password;
#[forbid(unsafe_code)]
pub mod public;
#[forbid(unsafe_code)]
mod util;
use std::fmt::{self, Debug, Display, Formatter};
use boringssl::BoringError;
/// Errors generated by this crate.
///
/// `Error` represents two types of errors: errors generated by BoringSSL, and
/// errors generated by the Rust code in this crate. When printed (using either
/// `Display` or `Debug`), BoringSSL errors are of the form `boringssl:
/// <error>`, while errors generated by Rust code are of the form `<error>`.
pub struct Error(ErrorInner);
impl Error {
fn new(s: String) -> Error {
Error(ErrorInner::Mundane(s))
}
}
#[doc(hidden)]
impl From<BoringError> for Error {
fn from(err: BoringError) -> Error {
Error(ErrorInner::Boring(err))
}
}
impl Display for Error {
fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
match &self.0 {
ErrorInner::Mundane(err) => write!(f, "{}", err),
ErrorInner::Boring(err) => write!(f, "boringssl: {}", err),
}
}
}
impl Debug for Error {
fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
match &self.0 {
ErrorInner::Mundane(err) => write!(f, "{}", err),
ErrorInner::Boring(err) => {
if err.stack_depth() == 1 {
// Either there was no stack trace, or the stack trace only
// contained a single frame. In either case, don't bother
// printing a preceding newline.
write!(f, "boringssl: {:?}", err)
} else {
// There's a multi-line stack trace, so print a preceding
// newline.
write!(f, "boringssl:\n{:?}", err)
}
}
}
}
}
impl std::error::Error for Error {}
enum ErrorInner {
Mundane(String),
Boring(BoringError),
}
#[cfg(test)]
mod tests {
use super::Error;
#[test]
fn test_send() {
fn assert_send<T: Send>() {}
assert_send::<Error>();
}
#[test]
fn
|
() {
fn assert_sync<T: Sync>() {}
assert_sync::<Error>();
}
}
|
test_sync
|
identifier_name
|
lib.rs
|
// Copyright 2018 Google LLC
//
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file or at
// https://opensource.org/licenses/MIT.
//! Cryptography in Rust.
//!
//! Mundane is a Rust cryptography library backed by BoringSSL that is difficult
//! to misuse, ergonomic, and performant (in that order).
//!
//! # Features
//!
//! By default, Mundane provides only high-level cryptographic primitives.
//! Unless you are implementing cryptographic protocols, these high-level
//! primitives should be all you need. However, if you are sure that you need
//! something lower level, Mundane provides features to enable a number of
//! different low level primitives.
//!
//! WARNING: Being low level, these primitives provide the programmer with more
//! degrees of freedom. There are more conditions that the programmer must meet
//! in order to guarantee security, and thus more ways for the programmer to
//! shoot themself in the foot. Please only use these primitives if you're aware
//! of the risks and are comfortable with the responsibility of using them
//! correctly!
//!
//! **Features**
//!
//! | Name | Description |
//! | -------------- | ------------------------------------|
//! | `kdf` | Key derivation functions |
//! | `bytes` | Low-level operations on byte slices |
//! | `rsa-pkcs1v15` | RSA-PKCS1v1.5 signatures |
//!
//! # Insecure Operations
//!
//! Mundane supports one additional feature not listed in the previous section:
//! `insecure`. This enables some cryptographic primitives which are today
//! considered insecure. These should only be used for compatibility with legacy
//! systems - never in new systems! When the `insecure` feature is used, an
//! `insecure` module is added to the crate root. All insecure primitives are
//! exposed through this module.
#![deny(missing_docs)]
#![deny(warnings)]
// just in case we forget to add #[forbid(unsafe_code)] on new module
// definitions
#![deny(unsafe_code)]
#[macro_use]
mod macros;
// Forbid unsafe code except in the boringssl module.
#[allow(unsafe_code)]
mod boringssl;
#[cfg(any(doc, feature = "bytes"))]
#[forbid(unsafe_code)]
pub mod bytes;
#[forbid(unsafe_code)]
pub mod hash;
#[forbid(unsafe_code)]
pub mod hmac;
#[cfg(any(doc, feature = "insecure"))]
#[forbid(unsafe_code)]
pub mod insecure;
#[cfg(any(doc, feature = "kdf"))]
#[forbid(unsafe_code)]
pub mod kdf;
#[forbid(unsafe_code)]
pub mod password;
#[forbid(unsafe_code)]
pub mod public;
#[forbid(unsafe_code)]
mod util;
use std::fmt::{self, Debug, Display, Formatter};
use boringssl::BoringError;
/// Errors generated by this crate.
///
/// `Error` represents two types of errors: errors generated by BoringSSL, and
/// errors generated by the Rust code in this crate. When printed (using either
/// `Display` or `Debug`), BoringSSL errors are of the form `boringssl:
/// <error>`, while errors generated by Rust code are of the form `<error>`.
pub struct Error(ErrorInner);
impl Error {
fn new(s: String) -> Error {
Error(ErrorInner::Mundane(s))
}
}
#[doc(hidden)]
impl From<BoringError> for Error {
fn from(err: BoringError) -> Error {
Error(ErrorInner::Boring(err))
}
}
impl Display for Error {
fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
match &self.0 {
ErrorInner::Mundane(err) => write!(f, "{}", err),
ErrorInner::Boring(err) => write!(f, "boringssl: {}", err),
}
}
}
impl Debug for Error {
fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
match &self.0 {
ErrorInner::Mundane(err) => write!(f, "{}", err),
ErrorInner::Boring(err) => {
if err.stack_depth() == 1 {
// Either there was no stack trace, or the stack trace only
// contained a single frame. In either case, don't bother
// printing a preceding newline.
write!(f, "boringssl: {:?}", err)
} else {
// There's a multi-line stack trace, so print a preceding
// newline.
write!(f, "boringssl:\n{:?}", err)
}
}
}
}
}
impl std::error::Error for Error {}
enum ErrorInner {
Mundane(String),
Boring(BoringError),
}
#[cfg(test)]
mod tests {
use super::Error;
#[test]
fn test_send()
|
#[test]
fn test_sync() {
fn assert_sync<T: Sync>() {}
assert_sync::<Error>();
}
}
|
{
fn assert_send<T: Send>() {}
assert_send::<Error>();
}
|
identifier_body
|
obarray.rs
|
//! obarray code
use libc;
use remacs_macros::lisp_fn;
use remacs_sys::{Fpurecopy, Lisp_Object};
use remacs_sys::{check_obarray, check_vobarray, globals, intern_driver, make_unibyte_string,
oblookup};
use lisp::LispObject;
use lisp::defsubr;
/// A lisp object containing an `obarray`.
pub struct LispObarrayRef(LispObject);
impl LispObarrayRef {
/// Return a reference to the Lisp variable `obarray`.
pub fn constant_obarray() -> LispObarrayRef {
LispObarrayRef(LispObject::from(unsafe { check_vobarray() }))
}
/// Return a reference corresponding to OBJECT, or raise an error if it is
/// not a `LispObarrayRef`.
///
/// # C Porting Notes
///
/// This is a wrapper around the C function `check_obarray` instead of a
/// translation, so that fatal errors are handled in the same fashion.
pub fn from_object_or_error(object: LispObject) -> LispObarrayRef {
LispObarrayRef(LispObject::from(unsafe { check_obarray(object.to_raw()) }))
}
/// Return the symbol that matches C string S, of length LEN. If there is no
/// such symbol, return the integer bucket number of where the symbol would
/// be if it were present.
///
/// # C Porting Notes
///
/// This is a wrapper around the C function `oblookup`. It uses LEN as both
/// the byte and char length, i.e. S is treated as a unibyte string.
pub fn lookup_cstring(&self, s: *const libc::c_char, len: libc::ptrdiff_t) -> LispObject {
LispObject::from(unsafe { oblookup(self.0.to_raw(), s, len, len) })
}
/// Intern the C string S, of length LEN. That is, return the new or
/// existing symbol with that name in this `LispObarrayRef`.
///
/// # C Porting Notes
///
/// This is makes use of the C function `intern_driver`. It uses LEN as both
/// the byte and char length, i.e. S is treated as a unibyte string.
pub fn intern_cstring(&mut self, s: *const libc::c_char, len: libc::ptrdiff_t) -> LispObject {
let tem = self.lookup_cstring(s, len);
if tem.is_symbol() {
tem
} else {
// The above `oblookup' was done on the basis of nchars==nbytes, so
// the string has to be unibyte.
LispObject::from(unsafe {
intern_driver(make_unibyte_string(s, len), self.0.to_raw(), tem.to_raw())
})
}
}
/// Return the symbol that matches NAME (either a symbol or string). If
/// there is no such symbol, return the integer bucket number of where the
/// symbol would be if it were present.
///
/// # C Porting Notes
///
/// This is a wrapper around the C function `oblookup`. It is capable of
/// handling multibyte strings, unlike intern_1 and friends.
pub fn lookup(&self, name: LispObject) -> LispObject {
let string = name.symbol_or_string_as_string();
LispObject::from(unsafe {
oblookup(
self.0.to_raw(),
string.const_sdata_ptr(),
string.len_chars(),
string.len_bytes(),
)
})
}
/// Intern the string or symbol STRING. That is, return the new or existing
/// symbol with that name in this `LispObarrayRef`. If Emacs is loading Lisp
/// code to dump to an executable (ie. `purify-flag` is `t`), the symbol
/// name will be transferred to pure storage.
///
/// # C Porting Notes
///
/// This is makes use of the C function `intern_driver`. It is capable of
/// handling multibyte strings, unlike `intern_cstring`.
pub fn
|
(&mut self, string: LispObject) -> LispObject {
let tem = self.lookup(string);
if tem.is_symbol() {
tem
} else if LispObject::from(unsafe { globals.f_Vpurify_flag }).is_not_nil() {
// When Emacs is running lisp code to dump to an executable, make
// use of pure storage.
LispObject::from(unsafe {
intern_driver(Fpurecopy(string.to_raw()), self.0.to_raw(), tem.to_raw())
})
} else {
LispObject::from(unsafe {
intern_driver(string.to_raw(), self.0.to_raw(), tem.to_raw())
})
}
}
}
/// Intern the C string `s`: return a symbol with that name, interned in the
/// current obarray.
#[no_mangle]
pub extern "C" fn intern_1(s: *const libc::c_char, len: libc::ptrdiff_t) -> Lisp_Object {
LispObarrayRef::constant_obarray()
.intern_cstring(s, len)
.to_raw()
}
/// Return the canonical symbol named NAME, or nil if none exists.
/// NAME may be a string or a symbol. If it is a symbol, that exact
/// symbol is searched for.
/// A second optional argument specifies the obarray to use;
/// it defaults to the value of `obarray'.
#[lisp_fn(min = "1")]
fn intern_soft(name: LispObject, obarray: LispObject) -> LispObject {
let tem = if obarray.is_nil() {
LispObarrayRef::constant_obarray().lookup(name)
} else {
LispObarrayRef::from_object_or_error(obarray).lookup(name)
};
if tem.is_integer() || (name.is_symbol() &&!name.eq(tem)) {
LispObject::constant_nil()
} else {
tem
}
}
/// Return the canonical symbol whose name is STRING.
/// If there is none, one is created by this function and returned.
/// A second optional argument specifies the obarray to use;
/// it defaults to the value of `obarray'.
#[lisp_fn(min = "1")]
fn intern(string: LispObject, obarray: LispObject) -> LispObject {
if obarray.is_nil() {
LispObarrayRef::constant_obarray().intern(string)
} else {
LispObarrayRef::from_object_or_error(obarray).intern(string)
}
}
include!(concat!(env!("OUT_DIR"), "/obarray_exports.rs"));
|
intern
|
identifier_name
|
obarray.rs
|
//! obarray code
use libc;
use remacs_macros::lisp_fn;
use remacs_sys::{Fpurecopy, Lisp_Object};
use remacs_sys::{check_obarray, check_vobarray, globals, intern_driver, make_unibyte_string,
oblookup};
use lisp::LispObject;
use lisp::defsubr;
/// A lisp object containing an `obarray`.
pub struct LispObarrayRef(LispObject);
impl LispObarrayRef {
/// Return a reference to the Lisp variable `obarray`.
pub fn constant_obarray() -> LispObarrayRef {
LispObarrayRef(LispObject::from(unsafe { check_vobarray() }))
}
/// Return a reference corresponding to OBJECT, or raise an error if it is
/// not a `LispObarrayRef`.
///
/// # C Porting Notes
///
/// This is a wrapper around the C function `check_obarray` instead of a
/// translation, so that fatal errors are handled in the same fashion.
pub fn from_object_or_error(object: LispObject) -> LispObarrayRef {
LispObarrayRef(LispObject::from(unsafe { check_obarray(object.to_raw()) }))
}
/// Return the symbol that matches C string S, of length LEN. If there is no
/// such symbol, return the integer bucket number of where the symbol would
/// be if it were present.
///
/// # C Porting Notes
///
/// This is a wrapper around the C function `oblookup`. It uses LEN as both
/// the byte and char length, i.e. S is treated as a unibyte string.
pub fn lookup_cstring(&self, s: *const libc::c_char, len: libc::ptrdiff_t) -> LispObject {
LispObject::from(unsafe { oblookup(self.0.to_raw(), s, len, len) })
}
/// Intern the C string S, of length LEN. That is, return the new or
/// existing symbol with that name in this `LispObarrayRef`.
///
/// # C Porting Notes
///
/// This is makes use of the C function `intern_driver`. It uses LEN as both
/// the byte and char length, i.e. S is treated as a unibyte string.
pub fn intern_cstring(&mut self, s: *const libc::c_char, len: libc::ptrdiff_t) -> LispObject {
let tem = self.lookup_cstring(s, len);
if tem.is_symbol() {
tem
} else {
// The above `oblookup' was done on the basis of nchars==nbytes, so
// the string has to be unibyte.
LispObject::from(unsafe {
intern_driver(make_unibyte_string(s, len), self.0.to_raw(), tem.to_raw())
})
}
}
|
/// Return the symbol that matches NAME (either a symbol or string). If
/// there is no such symbol, return the integer bucket number of where the
/// symbol would be if it were present.
///
/// # C Porting Notes
///
/// This is a wrapper around the C function `oblookup`. It is capable of
/// handling multibyte strings, unlike intern_1 and friends.
pub fn lookup(&self, name: LispObject) -> LispObject {
let string = name.symbol_or_string_as_string();
LispObject::from(unsafe {
oblookup(
self.0.to_raw(),
string.const_sdata_ptr(),
string.len_chars(),
string.len_bytes(),
)
})
}
/// Intern the string or symbol STRING. That is, return the new or existing
/// symbol with that name in this `LispObarrayRef`. If Emacs is loading Lisp
/// code to dump to an executable (ie. `purify-flag` is `t`), the symbol
/// name will be transferred to pure storage.
///
/// # C Porting Notes
///
/// This is makes use of the C function `intern_driver`. It is capable of
/// handling multibyte strings, unlike `intern_cstring`.
pub fn intern(&mut self, string: LispObject) -> LispObject {
let tem = self.lookup(string);
if tem.is_symbol() {
tem
} else if LispObject::from(unsafe { globals.f_Vpurify_flag }).is_not_nil() {
// When Emacs is running lisp code to dump to an executable, make
// use of pure storage.
LispObject::from(unsafe {
intern_driver(Fpurecopy(string.to_raw()), self.0.to_raw(), tem.to_raw())
})
} else {
LispObject::from(unsafe {
intern_driver(string.to_raw(), self.0.to_raw(), tem.to_raw())
})
}
}
}
/// Intern the C string `s`: return a symbol with that name, interned in the
/// current obarray.
#[no_mangle]
pub extern "C" fn intern_1(s: *const libc::c_char, len: libc::ptrdiff_t) -> Lisp_Object {
LispObarrayRef::constant_obarray()
.intern_cstring(s, len)
.to_raw()
}
/// Return the canonical symbol named NAME, or nil if none exists.
/// NAME may be a string or a symbol. If it is a symbol, that exact
/// symbol is searched for.
/// A second optional argument specifies the obarray to use;
/// it defaults to the value of `obarray'.
#[lisp_fn(min = "1")]
fn intern_soft(name: LispObject, obarray: LispObject) -> LispObject {
let tem = if obarray.is_nil() {
LispObarrayRef::constant_obarray().lookup(name)
} else {
LispObarrayRef::from_object_or_error(obarray).lookup(name)
};
if tem.is_integer() || (name.is_symbol() &&!name.eq(tem)) {
LispObject::constant_nil()
} else {
tem
}
}
/// Return the canonical symbol whose name is STRING.
/// If there is none, one is created by this function and returned.
/// A second optional argument specifies the obarray to use;
/// it defaults to the value of `obarray'.
#[lisp_fn(min = "1")]
fn intern(string: LispObject, obarray: LispObject) -> LispObject {
if obarray.is_nil() {
LispObarrayRef::constant_obarray().intern(string)
} else {
LispObarrayRef::from_object_or_error(obarray).intern(string)
}
}
include!(concat!(env!("OUT_DIR"), "/obarray_exports.rs"));
|
random_line_split
|
|
obarray.rs
|
//! obarray code
use libc;
use remacs_macros::lisp_fn;
use remacs_sys::{Fpurecopy, Lisp_Object};
use remacs_sys::{check_obarray, check_vobarray, globals, intern_driver, make_unibyte_string,
oblookup};
use lisp::LispObject;
use lisp::defsubr;
/// A lisp object containing an `obarray`.
pub struct LispObarrayRef(LispObject);
impl LispObarrayRef {
/// Return a reference to the Lisp variable `obarray`.
pub fn constant_obarray() -> LispObarrayRef {
LispObarrayRef(LispObject::from(unsafe { check_vobarray() }))
}
/// Return a reference corresponding to OBJECT, or raise an error if it is
/// not a `LispObarrayRef`.
///
/// # C Porting Notes
///
/// This is a wrapper around the C function `check_obarray` instead of a
/// translation, so that fatal errors are handled in the same fashion.
pub fn from_object_or_error(object: LispObject) -> LispObarrayRef {
LispObarrayRef(LispObject::from(unsafe { check_obarray(object.to_raw()) }))
}
/// Return the symbol that matches C string S, of length LEN. If there is no
/// such symbol, return the integer bucket number of where the symbol would
/// be if it were present.
///
/// # C Porting Notes
///
/// This is a wrapper around the C function `oblookup`. It uses LEN as both
/// the byte and char length, i.e. S is treated as a unibyte string.
pub fn lookup_cstring(&self, s: *const libc::c_char, len: libc::ptrdiff_t) -> LispObject {
LispObject::from(unsafe { oblookup(self.0.to_raw(), s, len, len) })
}
/// Intern the C string S, of length LEN. That is, return the new or
/// existing symbol with that name in this `LispObarrayRef`.
///
/// # C Porting Notes
///
/// This is makes use of the C function `intern_driver`. It uses LEN as both
/// the byte and char length, i.e. S is treated as a unibyte string.
pub fn intern_cstring(&mut self, s: *const libc::c_char, len: libc::ptrdiff_t) -> LispObject {
let tem = self.lookup_cstring(s, len);
if tem.is_symbol() {
tem
} else {
// The above `oblookup' was done on the basis of nchars==nbytes, so
// the string has to be unibyte.
LispObject::from(unsafe {
intern_driver(make_unibyte_string(s, len), self.0.to_raw(), tem.to_raw())
})
}
}
/// Return the symbol that matches NAME (either a symbol or string). If
/// there is no such symbol, return the integer bucket number of where the
/// symbol would be if it were present.
///
/// # C Porting Notes
///
/// This is a wrapper around the C function `oblookup`. It is capable of
/// handling multibyte strings, unlike intern_1 and friends.
pub fn lookup(&self, name: LispObject) -> LispObject {
let string = name.symbol_or_string_as_string();
LispObject::from(unsafe {
oblookup(
self.0.to_raw(),
string.const_sdata_ptr(),
string.len_chars(),
string.len_bytes(),
)
})
}
/// Intern the string or symbol STRING. That is, return the new or existing
/// symbol with that name in this `LispObarrayRef`. If Emacs is loading Lisp
/// code to dump to an executable (ie. `purify-flag` is `t`), the symbol
/// name will be transferred to pure storage.
///
/// # C Porting Notes
///
/// This is makes use of the C function `intern_driver`. It is capable of
/// handling multibyte strings, unlike `intern_cstring`.
pub fn intern(&mut self, string: LispObject) -> LispObject {
let tem = self.lookup(string);
if tem.is_symbol() {
tem
} else if LispObject::from(unsafe { globals.f_Vpurify_flag }).is_not_nil() {
// When Emacs is running lisp code to dump to an executable, make
// use of pure storage.
LispObject::from(unsafe {
intern_driver(Fpurecopy(string.to_raw()), self.0.to_raw(), tem.to_raw())
})
} else {
LispObject::from(unsafe {
intern_driver(string.to_raw(), self.0.to_raw(), tem.to_raw())
})
}
}
}
/// Intern the C string `s`: return a symbol with that name, interned in the
/// current obarray.
#[no_mangle]
pub extern "C" fn intern_1(s: *const libc::c_char, len: libc::ptrdiff_t) -> Lisp_Object {
LispObarrayRef::constant_obarray()
.intern_cstring(s, len)
.to_raw()
}
/// Return the canonical symbol named NAME, or nil if none exists.
/// NAME may be a string or a symbol. If it is a symbol, that exact
/// symbol is searched for.
/// A second optional argument specifies the obarray to use;
/// it defaults to the value of `obarray'.
#[lisp_fn(min = "1")]
fn intern_soft(name: LispObject, obarray: LispObject) -> LispObject {
let tem = if obarray.is_nil() {
LispObarrayRef::constant_obarray().lookup(name)
} else {
LispObarrayRef::from_object_or_error(obarray).lookup(name)
};
if tem.is_integer() || (name.is_symbol() &&!name.eq(tem))
|
else {
tem
}
}
/// Return the canonical symbol whose name is STRING.
/// If there is none, one is created by this function and returned.
/// A second optional argument specifies the obarray to use;
/// it defaults to the value of `obarray'.
#[lisp_fn(min = "1")]
fn intern(string: LispObject, obarray: LispObject) -> LispObject {
if obarray.is_nil() {
LispObarrayRef::constant_obarray().intern(string)
} else {
LispObarrayRef::from_object_or_error(obarray).intern(string)
}
}
include!(concat!(env!("OUT_DIR"), "/obarray_exports.rs"));
|
{
LispObject::constant_nil()
}
|
conditional_block
|
xrinputsource.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 https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::XRInputSourceBinding;
use crate::dom::bindings::codegen::Bindings::XRInputSourceBinding::{
XRHandedness, XRInputSourceMethods,
};
use crate::dom::bindings::reflector::{reflect_dom_object, DomObject, Reflector};
use crate::dom::bindings::root::{Dom, DomRoot, MutNullableDom};
use crate::dom::globalscope::GlobalScope;
use crate::dom::xrsession::XRSession;
use crate::dom::xrspace::XRSpace;
use dom_struct::dom_struct;
use webxr_api::{Handedness, InputId, InputSource};
#[dom_struct]
pub struct XRInputSource {
reflector: Reflector,
session: Dom<XRSession>,
#[ignore_malloc_size_of = "Defined in rust-webvr"]
info: InputSource,
#[ignore_malloc_size_of = "Defined in rust-webvr"]
target_ray_space: MutNullableDom<XRSpace>,
}
impl XRInputSource {
pub fn new_inherited(session: &XRSession, info: InputSource) -> XRInputSource {
XRInputSource {
reflector: Reflector::new(),
session: Dom::from_ref(session),
info,
target_ray_space: Default::default(),
}
}
pub fn new(
global: &GlobalScope,
session: &XRSession,
info: InputSource,
) -> DomRoot<XRInputSource>
|
pub fn id(&self) -> InputId {
self.info.id
}
}
impl XRInputSourceMethods for XRInputSource {
/// https://immersive-web.github.io/webxr/#dom-xrinputsource-handedness
fn Handedness(&self) -> XRHandedness {
match self.info.handedness {
Handedness::None => XRHandedness::None,
Handedness::Left => XRHandedness::Left,
Handedness::Right => XRHandedness::Right,
}
}
/// https://immersive-web.github.io/webxr/#dom-xrinputsource-targetrayspace
fn TargetRaySpace(&self) -> DomRoot<XRSpace> {
self.target_ray_space.or_init(|| {
let global = self.global();
XRSpace::new_inputspace(&global, &self.session, &self)
})
}
}
|
{
reflect_dom_object(
Box::new(XRInputSource::new_inherited(session, info)),
global,
XRInputSourceBinding::Wrap,
)
}
|
identifier_body
|
xrinputsource.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 https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::XRInputSourceBinding;
use crate::dom::bindings::codegen::Bindings::XRInputSourceBinding::{
XRHandedness, XRInputSourceMethods,
};
use crate::dom::bindings::reflector::{reflect_dom_object, DomObject, Reflector};
use crate::dom::bindings::root::{Dom, DomRoot, MutNullableDom};
use crate::dom::globalscope::GlobalScope;
use crate::dom::xrsession::XRSession;
use crate::dom::xrspace::XRSpace;
use dom_struct::dom_struct;
use webxr_api::{Handedness, InputId, InputSource};
#[dom_struct]
pub struct XRInputSource {
reflector: Reflector,
session: Dom<XRSession>,
#[ignore_malloc_size_of = "Defined in rust-webvr"]
info: InputSource,
#[ignore_malloc_size_of = "Defined in rust-webvr"]
target_ray_space: MutNullableDom<XRSpace>,
}
impl XRInputSource {
pub fn new_inherited(session: &XRSession, info: InputSource) -> XRInputSource {
XRInputSource {
reflector: Reflector::new(),
session: Dom::from_ref(session),
info,
target_ray_space: Default::default(),
}
}
pub fn new(
global: &GlobalScope,
session: &XRSession,
info: InputSource,
) -> DomRoot<XRInputSource> {
reflect_dom_object(
Box::new(XRInputSource::new_inherited(session, info)),
global,
XRInputSourceBinding::Wrap,
)
}
pub fn id(&self) -> InputId {
self.info.id
}
}
impl XRInputSourceMethods for XRInputSource {
/// https://immersive-web.github.io/webxr/#dom-xrinputsource-handedness
fn Handedness(&self) -> XRHandedness {
|
Handedness::Right => XRHandedness::Right,
}
}
/// https://immersive-web.github.io/webxr/#dom-xrinputsource-targetrayspace
fn TargetRaySpace(&self) -> DomRoot<XRSpace> {
self.target_ray_space.or_init(|| {
let global = self.global();
XRSpace::new_inputspace(&global, &self.session, &self)
})
}
}
|
match self.info.handedness {
Handedness::None => XRHandedness::None,
Handedness::Left => XRHandedness::Left,
|
random_line_split
|
xrinputsource.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 https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::XRInputSourceBinding;
use crate::dom::bindings::codegen::Bindings::XRInputSourceBinding::{
XRHandedness, XRInputSourceMethods,
};
use crate::dom::bindings::reflector::{reflect_dom_object, DomObject, Reflector};
use crate::dom::bindings::root::{Dom, DomRoot, MutNullableDom};
use crate::dom::globalscope::GlobalScope;
use crate::dom::xrsession::XRSession;
use crate::dom::xrspace::XRSpace;
use dom_struct::dom_struct;
use webxr_api::{Handedness, InputId, InputSource};
#[dom_struct]
pub struct XRInputSource {
reflector: Reflector,
session: Dom<XRSession>,
#[ignore_malloc_size_of = "Defined in rust-webvr"]
info: InputSource,
#[ignore_malloc_size_of = "Defined in rust-webvr"]
target_ray_space: MutNullableDom<XRSpace>,
}
impl XRInputSource {
pub fn new_inherited(session: &XRSession, info: InputSource) -> XRInputSource {
XRInputSource {
reflector: Reflector::new(),
session: Dom::from_ref(session),
info,
target_ray_space: Default::default(),
}
}
pub fn
|
(
global: &GlobalScope,
session: &XRSession,
info: InputSource,
) -> DomRoot<XRInputSource> {
reflect_dom_object(
Box::new(XRInputSource::new_inherited(session, info)),
global,
XRInputSourceBinding::Wrap,
)
}
pub fn id(&self) -> InputId {
self.info.id
}
}
impl XRInputSourceMethods for XRInputSource {
/// https://immersive-web.github.io/webxr/#dom-xrinputsource-handedness
fn Handedness(&self) -> XRHandedness {
match self.info.handedness {
Handedness::None => XRHandedness::None,
Handedness::Left => XRHandedness::Left,
Handedness::Right => XRHandedness::Right,
}
}
/// https://immersive-web.github.io/webxr/#dom-xrinputsource-targetrayspace
fn TargetRaySpace(&self) -> DomRoot<XRSpace> {
self.target_ray_space.or_init(|| {
let global = self.global();
XRSpace::new_inputspace(&global, &self.session, &self)
})
}
}
|
new
|
identifier_name
|
random_ordered_unique_vecs.rs
|
use core::hash::Hash;
use itertools::Itertools;
use malachite_base::chars::exhaustive::exhaustive_chars;
use malachite_base::chars::random::graphic_weighted_random_char_inclusive_range;
use malachite_base::num::random::geometric::geometric_random_unsigneds;
use malachite_base::num::random::random_primitive_ints;
use malachite_base::random::{Seed, EXAMPLE_SEED};
use malachite_base::vecs::random::random_ordered_unique_vecs;
use malachite_base_test_util::stats::common_values_map::common_values_map_debug;
use malachite_base_test_util::stats::median;
use std::fmt::Debug;
fn random_ordered_unique_vecs_helper<
T: Clone + Debug + Eq + Hash + Ord,
I: Clone + Iterator<Item = T>,
>(
xs_gen: &dyn Fn(Seed) -> I,
mean_length_numerator: u64,
mean_length_denominator: u64,
expected_values: &[Vec<T>],
expected_common_values: &[(Vec<T>, usize)],
expected_median: (Vec<T>, Option<Vec<T>>),
) {
let xs = random_ordered_unique_vecs(
EXAMPLE_SEED,
xs_gen,
mean_length_numerator,
mean_length_denominator,
);
let values = xs.clone().take(20).collect_vec();
let common_values = common_values_map_debug(1000000, 10, xs.clone());
let median = median(xs.take(1000000));
assert_eq!(
(values.as_slice(), common_values.as_slice(), median),
(expected_values, expected_common_values, expected_median)
);
}
#[test]
fn test_random_ordered_unique_vecs()
|
vec![52, 69, 73, 91, 115, 137, 153, 178],
vec![],
vec![34, 95, 112],
vec![],
vec![106, 130, 167, 168, 197],
vec![86, 101, 122, 150, 172, 177, 207, 218, 221],
],
&[
(vec![], 199913),
(vec![7], 705),
(vec![25], 689),
(vec![184], 681),
(vec![213], 681),
(vec![255], 676),
(vec![215], 675),
(vec![54], 673),
(vec![122], 672),
(vec![207], 672),
],
(vec![27, 31, 211, 238], Some(vec![27, 31, 247, 251])),
);
random_ordered_unique_vecs_helper(
&|seed| geometric_random_unsigneds::<u32>(seed, 32, 1),
4,
1,
&[
vec![],
vec![1, 9, 12, 14, 16, 17, 19, 21, 41, 42, 68, 79, 124, 141],
vec![0, 1, 10, 99],
vec![2, 12, 36, 77],
vec![1],
vec![],
vec![1, 5, 9, 19, 103],
vec![6, 7],
vec![15, 18, 51, 159],
vec![],
vec![2, 26, 40, 52, 64, 75],
vec![],
vec![],
vec![3, 4, 5, 7, 30, 31, 34, 43, 49, 51, 67],
vec![1, 14, 16, 24, 29, 41, 47, 52],
vec![],
vec![11, 13, 62],
vec![],
vec![3, 14, 42, 47, 109],
vec![5, 13, 16, 25, 37, 41, 42, 86, 96],
],
&[
(vec![], 199913),
(vec![0], 4861),
(vec![1], 4593),
(vec![2], 4498),
(vec![3], 4405),
(vec![4], 4330),
(vec![5], 4078),
(vec![6], 4050),
(vec![7], 3858),
(vec![8], 3848),
],
(
vec![3, 9, 14, 22, 36, 56, 107],
Some(vec![3, 9, 14, 22, 42, 54, 73, 150]),
),
);
random_ordered_unique_vecs_helper(
&random_primitive_ints::<u8>,
1,
4,
&[
vec![],
vec![],
vec![85],
vec![11],
vec![136, 200],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![134, 235],
vec![203],
vec![],
vec![38, 223],
vec![],
vec![],
vec![],
vec![],
],
&[
(vec![], 800023),
(vec![162], 692),
(vec![235], 690),
(vec![90], 688),
(vec![65], 687),
(vec![249], 686),
(vec![175], 684),
(vec![108], 683),
(vec![211], 682),
(vec![237], 680),
],
(vec![], None),
);
random_ordered_unique_vecs_helper(
&|seed| {
graphic_weighted_random_char_inclusive_range(
seed,
'a',
exhaustive_chars().nth(200).unwrap(),
1,
1,
)
},
4,
1,
&[
vec![],
vec!['g', 'q', '³', '»', 'À', 'Á', 'Ã', 'È', 'á', 'â', 'ì', 'ñ', 'Ā', 'ą'],
vec!['ª', '´', 'Ã', 'ä'],
vec!['½', 'Á', 'Ï', 'ý'],
vec!['j'],
vec![],
vec!['u', '½', 'Â', 'Ñ', 'ï'],
vec!['x', 'õ'],
vec!['¡', 'Â', 'ù', 'Ċ'],
vec![],
vec!['b', 'r','s', '¬', 'Â', 'Ñ'],
vec![],
vec![],
vec!['j', 'n', 't', '¬', 'º', '¿', 'Á', 'Ø', 'Þ', 'ô', 'ü'],
vec!['b', 'k', '±', 'Î', 'Ü', 'æ', 'è', 'ā'],
vec![],
vec!['«', '¹', 'Î'],
vec![],
vec!['~', '¯', '´', 'Ý', 'â'],
vec!['g', '¼', 'Ç', 'Î', 'Ü', 'Þ', 'æ', 'é', 'ö'],
],
&[
(vec![], 199913),
(vec!['Ó'], 1270),
(vec!['Â'], 1249),
(vec!['§'], 1244),
(vec!['¿'], 1243),
(vec!['õ'], 1241),
(vec!['ĉ'], 1234),
(vec!['¤'], 1232),
(vec!['¼'], 1232),
(vec!['Ì'], 1229),
],
(
vec!['o', 'v', '¢', '±', 'Ä', 'Ć'],
Some(vec!['o', 'v', '¢', '³', 'ã']),
),
);
}
#[test]
#[should_panic]
fn random_ordered_unique_vecs_fail_1() {
random
_ordered_unique_vecs(EXAMPLE_SEED, &random_primitive_ints::<u32>, 0, 1);
}
#[test]
#[should_panic]
fn random_ordered_unique_vecs_fail_2() {
random_ordered_unique_vecs(EXAMPLE_SEED, &random_primitive_ints::<u32>, 1, 0);
}
#[test]
#[should_panic]
fn random_ordered_unique_vecs_fail_3() {
random_ordered_unique_vecs(
EXAMPLE_SEED,
&random_primitive_ints::<u32>,
u64::MAX,
u64::MAX - 1,
);
}
|
{
random_ordered_unique_vecs_helper(
&random_primitive_ints::<u8>,
4,
1,
&[
vec![],
vec![11, 32, 38, 85, 134, 136, 162, 166, 177, 200, 203, 217, 223, 235],
vec![30, 90, 218, 234],
vec![9, 106, 204, 216],
vec![151],
vec![],
vec![78, 91, 97, 213, 253],
vec![39, 191],
vec![170, 175, 232, 233],
vec![],
vec![2, 22, 35, 114, 198, 217],
vec![],
vec![],
vec![17, 25, 32, 65, 79, 114, 121, 144, 148, 173, 222],
|
identifier_body
|
random_ordered_unique_vecs.rs
|
use core::hash::Hash;
use itertools::Itertools;
use malachite_base::chars::exhaustive::exhaustive_chars;
use malachite_base::chars::random::graphic_weighted_random_char_inclusive_range;
use malachite_base::num::random::geometric::geometric_random_unsigneds;
use malachite_base::num::random::random_primitive_ints;
use malachite_base::random::{Seed, EXAMPLE_SEED};
use malachite_base::vecs::random::random_ordered_unique_vecs;
use malachite_base_test_util::stats::common_values_map::common_values_map_debug;
use malachite_base_test_util::stats::median;
use std::fmt::Debug;
fn random_ordered_unique_vecs_helper<
T: Clone + Debug + Eq + Hash + Ord,
I: Clone + Iterator<Item = T>,
>(
xs_gen: &dyn Fn(Seed) -> I,
mean_length_numerator: u64,
mean_length_denominator: u64,
expected_values: &[Vec<T>],
expected_common_values: &[(Vec<T>, usize)],
expected_median: (Vec<T>, Option<Vec<T>>),
) {
let xs = random_ordered_unique_vecs(
EXAMPLE_SEED,
xs_gen,
mean_length_numerator,
mean_length_denominator,
);
let values = xs.clone().take(20).collect_vec();
let common_values = common_values_map_debug(1000000, 10, xs.clone());
let median = median(xs.take(1000000));
assert_eq!(
(values.as_slice(), common_values.as_slice(), median),
(expected_values, expected_common_values, expected_median)
);
}
#[test]
fn test_random_ordered_unique_vecs() {
random_ordered_unique_vecs_helper(
&random_primitive_ints::<u8>,
4,
1,
&[
vec![],
vec![11, 32, 38, 85, 134, 136, 162, 166, 177, 200, 203, 217, 223, 235],
vec![30, 90, 218, 234],
vec![9, 106, 204, 216],
vec![151],
vec![],
vec![78, 91, 97, 213, 253],
vec![39, 191],
vec![170, 175, 232, 233],
vec![],
vec![2, 22, 35, 114, 198, 217],
vec![],
vec![],
vec![17, 25, 32, 65, 79, 114, 121, 144, 148, 173, 222],
vec![52, 69, 73, 91, 115, 137, 153, 178],
vec![],
vec![34, 95, 112],
vec![],
vec![106, 130, 167, 168, 197],
vec![86, 101, 122, 150, 172, 177, 207, 218, 221],
],
&[
(vec![], 199913),
(vec![7], 705),
(vec![25], 689),
(vec![184], 681),
(vec![213], 681),
(vec![255], 676),
(vec![215], 675),
(vec![54], 673),
(vec![122], 672),
(vec![207], 672),
],
(vec![27, 31, 211, 238], Some(vec![27, 31, 247, 251])),
);
random_ordered_unique_vecs_helper(
&|seed| geometric_random_unsigneds::<u32>(seed, 32, 1),
4,
1,
&[
vec![],
vec![1, 9, 12, 14, 16, 17, 19, 21, 41, 42, 68, 79, 124, 141],
vec![0, 1, 10, 99],
vec![2, 12, 36, 77],
vec![1],
vec![],
vec![1, 5, 9, 19, 103],
vec![6, 7],
vec![15, 18, 51, 159],
vec![],
vec![2, 26, 40, 52, 64, 75],
vec![],
vec![],
vec![3, 4, 5, 7, 30, 31, 34, 43, 49, 51, 67],
vec![1, 14, 16, 24, 29, 41, 47, 52],
vec![],
vec![11, 13, 62],
vec![],
vec![3, 14, 42, 47, 109],
vec![5, 13, 16, 25, 37, 41, 42, 86, 96],
],
&[
(vec![], 199913),
(vec![0], 4861),
(vec![1], 4593),
(vec![2], 4498),
(vec![3], 4405),
(vec![4], 4330),
(vec![5], 4078),
(vec![6], 4050),
(vec![7], 3858),
(vec![8], 3848),
],
(
vec![3, 9, 14, 22, 36, 56, 107],
Some(vec![3, 9, 14, 22, 42, 54, 73, 150]),
),
);
random_ordered_unique_vecs_helper(
&random_primitive_ints::<u8>,
1,
4,
&[
vec![],
vec![],
vec![85],
vec![11],
vec![136, 200],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![134, 235],
vec![203],
vec![],
vec![38, 223],
vec![],
vec![],
vec![],
vec![],
],
&[
(vec![], 800023),
(vec![162], 692),
(vec![235], 690),
(vec![90], 688),
(vec![65], 687),
(vec![249], 686),
(vec![175], 684),
(vec![108], 683),
(vec![211], 682),
(vec![237], 680),
],
(vec![], None),
);
random_ordered_unique_vecs_helper(
&|seed| {
graphic_weighted_random_char_inclusive_range(
seed,
'a',
exhaustive_chars().nth(200).unwrap(),
1,
1,
)
},
4,
1,
&[
vec![],
vec!['g', 'q', '³', '»', 'À', 'Á', 'Ã', 'È', 'á', 'â', 'ì', 'ñ', 'Ā', 'ą'],
vec!['ª', '´', 'Ã', 'ä'],
vec!['½', 'Á', 'Ï', 'ý'],
vec!['j'],
vec![],
vec!['u', '½', 'Â', 'Ñ', 'ï'],
vec!['x', 'õ'],
vec!['¡', 'Â', 'ù', 'Ċ'],
vec![],
vec!['b', 'r','s', '¬', 'Â', 'Ñ'],
vec![],
vec![],
vec!['j', 'n', 't', '¬', 'º', '¿', 'Á', 'Ø', 'Þ', 'ô', 'ü'],
vec!['b', 'k', '±', 'Î', 'Ü', 'æ', 'è', 'ā'],
vec![],
vec!['«', '¹', 'Î'],
vec![],
vec!['~', '¯', '´', 'Ý', 'â'],
vec!['g', '¼', 'Ç', 'Î', 'Ü', 'Þ', 'æ', 'é', 'ö'],
],
&[
(vec![], 199913),
(vec!['Ó'], 1270),
(vec!['Â'], 1249),
(vec!['§'], 1244),
(vec!['¿'], 1243),
(vec!['õ'], 1241),
(vec!['ĉ'], 1234),
(vec!['¤'], 1232),
(vec!['¼'], 1232),
(vec!['Ì'], 1229),
],
(
vec!['o', 'v', '¢', '±', 'Ä', 'Ć'],
Some(vec!['o', 'v', '¢', '³', 'ã']),
),
);
}
#[test]
|
#[test]
#[should_panic]
fn random_ordered_unique_vecs_fail_2() {
random_ordered_unique_vecs(EXAMPLE_SEED, &random_primitive_ints::<u32>, 1, 0);
}
#[test]
#[should_panic]
fn random_ordered_unique_vecs_fail_3() {
random_ordered_unique_vecs(
EXAMPLE_SEED,
&random_primitive_ints::<u32>,
u64::MAX,
u64::MAX - 1,
);
}
|
#[should_panic]
fn random_ordered_unique_vecs_fail_1() {
random_ordered_unique_vecs(EXAMPLE_SEED, &random_primitive_ints::<u32>, 0, 1);
}
|
random_line_split
|
random_ordered_unique_vecs.rs
|
use core::hash::Hash;
use itertools::Itertools;
use malachite_base::chars::exhaustive::exhaustive_chars;
use malachite_base::chars::random::graphic_weighted_random_char_inclusive_range;
use malachite_base::num::random::geometric::geometric_random_unsigneds;
use malachite_base::num::random::random_primitive_ints;
use malachite_base::random::{Seed, EXAMPLE_SEED};
use malachite_base::vecs::random::random_ordered_unique_vecs;
use malachite_base_test_util::stats::common_values_map::common_values_map_debug;
use malachite_base_test_util::stats::median;
use std::fmt::Debug;
fn random_ordered_unique_vecs_helper<
T: Clone + Debug + Eq + Hash + Ord,
I: Clone + Iterator<Item = T>,
>(
xs_gen: &dyn Fn(Seed) -> I,
mean_length_numerator: u64,
mean_length_denominator: u64,
expected_values: &[Vec<T>],
expected_common_values: &[(Vec<T>, usize)],
expected_median: (Vec<T>, Option<Vec<T>>),
) {
let xs = random_ordered_unique_vecs(
EXAMPLE_SEED,
xs_gen,
mean_length_numerator,
mean_length_denominator,
);
let values = xs.clone().take(20).collect_vec();
let common_values = common_values_map_debug(1000000, 10, xs.clone());
let median = median(xs.take(1000000));
assert_eq!(
(values.as_slice(), common_values.as_slice(), median),
(expected_values, expected_common_values, expected_median)
);
}
#[test]
fn test_random_ordered_unique_vecs() {
random_ordered_unique_vecs_helper(
&random_primitive_ints::<u8>,
4,
1,
&[
vec![],
vec![11, 32, 38, 85, 134, 136, 162, 166, 177, 200, 203, 217, 223, 235],
vec![30, 90, 218, 234],
vec![9, 106, 204, 216],
vec![151],
vec![],
vec![78, 91, 97, 213, 253],
vec![39, 191],
vec![170, 175, 232, 233],
vec![],
vec![2, 22, 35, 114, 198, 217],
vec![],
vec![],
vec![17, 25, 32, 65, 79, 114, 121, 144, 148, 173, 222],
vec![52, 69, 73, 91, 115, 137, 153, 178],
vec![],
vec![34, 95, 112],
vec![],
vec![106, 130, 167, 168, 197],
vec![86, 101, 122, 150, 172, 177, 207, 218, 221],
],
&[
(vec![], 199913),
(vec![7], 705),
(vec![25], 689),
(vec![184], 681),
(vec![213], 681),
(vec![255], 676),
(vec![215], 675),
(vec![54], 673),
(vec![122], 672),
(vec![207], 672),
],
(vec![27, 31, 211, 238], Some(vec![27, 31, 247, 251])),
);
random_ordered_unique_vecs_helper(
&|seed| geometric_random_unsigneds::<u32>(seed, 32, 1),
4,
1,
&[
vec![],
vec![1, 9, 12, 14, 16, 17, 19, 21, 41, 42, 68, 79, 124, 141],
vec![0, 1, 10, 99],
vec![2, 12, 36, 77],
vec![1],
vec![],
vec![1, 5, 9, 19, 103],
vec![6, 7],
vec![15, 18, 51, 159],
vec![],
vec![2, 26, 40, 52, 64, 75],
vec![],
vec![],
vec![3, 4, 5, 7, 30, 31, 34, 43, 49, 51, 67],
vec![1, 14, 16, 24, 29, 41, 47, 52],
vec![],
vec![11, 13, 62],
vec![],
vec![3, 14, 42, 47, 109],
vec![5, 13, 16, 25, 37, 41, 42, 86, 96],
],
&[
(vec![], 199913),
(vec![0], 4861),
(vec![1], 4593),
(vec![2], 4498),
(vec![3], 4405),
(vec![4], 4330),
(vec![5], 4078),
(vec![6], 4050),
(vec![7], 3858),
(vec![8], 3848),
],
(
vec![3, 9, 14, 22, 36, 56, 107],
Some(vec![3, 9, 14, 22, 42, 54, 73, 150]),
),
);
random_ordered_unique_vecs_helper(
&random_primitive_ints::<u8>,
1,
4,
&[
vec![],
vec![],
vec![85],
vec![11],
vec![136, 200],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![134, 235],
vec![203],
vec![],
vec![38, 223],
vec![],
vec![],
vec![],
vec![],
],
&[
(vec![], 800023),
(vec![162], 692),
(vec![235], 690),
(vec![90], 688),
(vec![65], 687),
(vec![249], 686),
(vec![175], 684),
(vec![108], 683),
(vec![211], 682),
(vec![237], 680),
],
(vec![], None),
);
random_ordered_unique_vecs_helper(
&|seed| {
graphic_weighted_random_char_inclusive_range(
seed,
'a',
exhaustive_chars().nth(200).unwrap(),
1,
1,
)
},
4,
1,
&[
vec![],
vec!['g', 'q', '³', '»', 'À', 'Á', 'Ã', 'È', 'á', 'â', 'ì', 'ñ', 'Ā', 'ą'],
vec!['ª', '´', 'Ã', 'ä'],
vec!['½', 'Á', 'Ï', 'ý'],
vec!['j'],
vec![],
vec!['u', '½', 'Â', 'Ñ', 'ï'],
vec!['x', 'õ'],
vec!['¡', 'Â', 'ù', 'Ċ'],
vec![],
vec!['b', 'r','s', '¬', 'Â', 'Ñ'],
vec![],
vec![],
vec!['j', 'n', 't', '¬', 'º', '¿', 'Á', 'Ø', 'Þ', 'ô', 'ü'],
vec!['b', 'k', '±', 'Î', 'Ü', 'æ', 'è', 'ā'],
vec![],
vec!['«', '¹', 'Î'],
vec![],
vec!['~', '¯', '´', 'Ý', 'â'],
vec!['g', '¼', 'Ç', 'Î', 'Ü', 'Þ', 'æ', 'é', 'ö'],
],
&[
(vec![], 199913),
(vec!['Ó'], 1270),
(vec!['Â'], 1249),
(vec!['§'], 1244),
(vec!['¿'], 1243),
(vec!['õ'], 1241),
(vec!['ĉ'], 1234),
(vec!['¤'], 1232),
(vec!['¼'], 1232),
(vec!['Ì'], 1229),
],
(
vec!['o', 'v', '¢', '±', 'Ä', 'Ć'],
Some(vec!['o', 'v', '¢', '³', 'ã']),
),
);
}
#[test]
#[should_panic]
fn random_ordered_unique_vecs_fail_1() {
random_ordered_unique_vecs(EXAMPLE_SEED, &random_primitive_ints::<u32>, 0, 1);
}
#[test]
#[should_panic]
fn random_ordered_unique_vecs_fail_2() {
random_ordered_unique_vecs(EXAMPLE_
|
2>, 1, 0);
}
#[test]
#[should_panic]
fn random_ordered_unique_vecs_fail_3() {
random_ordered_unique_vecs(
EXAMPLE_SEED,
&random_primitive_ints::<u32>,
u64::MAX,
u64::MAX - 1,
);
}
|
SEED, &random_primitive_ints::<u3
|
identifier_name
|
protocol_trait.rs
|
// Copyright 2016 Alexander Reece
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::io;
use inflections::Inflect;
use WriteRust;
use common::Specs;
pub struct ProtocolTraitWriter<'a> {
specs: &'a Specs<'a>,
}
impl<'a> WriteRust for ProtocolTraitWriter<'a> {
fn write_rust_to<W>(&self, writer: &mut W) -> io::Result<()>
where W: io::Write
{
try!(writeln!(
writer,
"pub trait Protocol<'a> {{\n\
type Frame: 'a;\n\
\n\
fn protocol_header() -> &'static [u8];\n"
));
for method in self.specs.methods() {
try!(writeln!(
writer,
"fn {class}_{snake_method}() -> <Self as ::method::{class}::{pascal_method}Method{lifetimes}>::Payload\n\
where Self: ::method::{class}::{pascal_method}Method{lifetimes}\n\
{{\n\
Default::default()\n\
}}",
lifetimes = if method.has_lifetimes() { "<'a>" } else { "" },
class = method.class_name().to_snake_case(),
snake_method = method.method_name().to_snake_case(),
pascal_method = method.method_name().to_pascal_case(),
))
}
try!(writeln!(writer, "}} // pub trait Protocol<'a>"));
Ok(())
}
|
specs: specs
}
}
}
|
}
impl<'a> ProtocolTraitWriter<'a> {
pub fn new(specs: &'a Specs<'a>) -> Self {
ProtocolTraitWriter {
|
random_line_split
|
protocol_trait.rs
|
// Copyright 2016 Alexander Reece
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::io;
use inflections::Inflect;
use WriteRust;
use common::Specs;
pub struct ProtocolTraitWriter<'a> {
specs: &'a Specs<'a>,
}
impl<'a> WriteRust for ProtocolTraitWriter<'a> {
fn
|
<W>(&self, writer: &mut W) -> io::Result<()>
where W: io::Write
{
try!(writeln!(
writer,
"pub trait Protocol<'a> {{\n\
type Frame: 'a;\n\
\n\
fn protocol_header() -> &'static [u8];\n"
));
for method in self.specs.methods() {
try!(writeln!(
writer,
"fn {class}_{snake_method}() -> <Self as ::method::{class}::{pascal_method}Method{lifetimes}>::Payload\n\
where Self: ::method::{class}::{pascal_method}Method{lifetimes}\n\
{{\n\
Default::default()\n\
}}",
lifetimes = if method.has_lifetimes() { "<'a>" } else { "" },
class = method.class_name().to_snake_case(),
snake_method = method.method_name().to_snake_case(),
pascal_method = method.method_name().to_pascal_case(),
))
}
try!(writeln!(writer, "}} // pub trait Protocol<'a>"));
Ok(())
}
}
impl<'a> ProtocolTraitWriter<'a> {
pub fn new(specs: &'a Specs<'a>) -> Self {
ProtocolTraitWriter {
specs: specs
}
}
}
|
write_rust_to
|
identifier_name
|
protocol_trait.rs
|
// Copyright 2016 Alexander Reece
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::io;
use inflections::Inflect;
use WriteRust;
use common::Specs;
pub struct ProtocolTraitWriter<'a> {
specs: &'a Specs<'a>,
}
impl<'a> WriteRust for ProtocolTraitWriter<'a> {
fn write_rust_to<W>(&self, writer: &mut W) -> io::Result<()>
where W: io::Write
|
pascal_method = method.method_name().to_pascal_case(),
))
}
try!(writeln!(writer, "}} // pub trait Protocol<'a>"));
Ok(())
}
}
impl<'a> ProtocolTraitWriter<'a> {
pub fn new(specs: &'a Specs<'a>) -> Self {
ProtocolTraitWriter {
specs: specs
}
}
}
|
{
try!(writeln!(
writer,
"pub trait Protocol<'a> {{\n\
type Frame: 'a;\n\
\n\
fn protocol_header() -> &'static [u8];\n"
));
for method in self.specs.methods() {
try!(writeln!(
writer,
"fn {class}_{snake_method}() -> <Self as ::method::{class}::{pascal_method}Method{lifetimes}>::Payload\n\
where Self: ::method::{class}::{pascal_method}Method{lifetimes}\n\
{{\n\
Default::default()\n\
}}",
lifetimes = if method.has_lifetimes() { "<'a>" } else { "" },
class = method.class_name().to_snake_case(),
snake_method = method.method_name().to_snake_case(),
|
identifier_body
|
receipt.rs
|
//! Endpoints for event receipts.
/// [POST /_matrix/client/r0/rooms/{roomId}/receipt/{receiptType}/{eventId}](https://matrix.org/docs/spec/client_server/r0.2.0.html#post-matrix-client-r0-rooms-roomid-receipt-receipttype-eventid)
pub mod create_receipt {
use ruma_identifiers::{EventId, RoomId};
use std::fmt::{Display, Error as FmtError, Formatter};
/// Details about this API endpoint.
#[derive(Clone, Copy, Debug)]
pub struct
|
;
/// This endpoint's path parameters.
#[derive(Clone, Debug)]
pub struct PathParams {
/// The event ID to acknowledge up to.
pub event_id: EventId,
/// The type of receipt to send.
pub receipt_type: ReceiptType,
/// The room in which to send the event.
pub room_id: RoomId,
}
/// The type of receipt.
#[derive(Clone, Copy, Debug)]
pub enum ReceiptType {
/// m.read
Read,
}
/// This API endpoint's response.
#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
pub struct Response;
impl<'de> ::Endpoint<'de> for Endpoint {
type BodyParams = ();
type PathParams = PathParams;
type QueryParams = ();
type Response = Response;
fn method() -> ::Method {
::Method::Post
}
fn request_path(params: Self::PathParams) -> String {
format!(
"/_matrix/client/r0/rooms/{}/receipt/{}/{}",
params.room_id,
params.receipt_type,
params.event_id
)
}
fn router_path() -> &'static str {
"/_matrix/client/r0/rooms/:room_id/receipt/:receipt_type/:event_id"
}
fn name() -> &'static str {
"create_receipt"
}
fn description() -> &'static str {
"Send a receipt event to a room."
}
fn requires_authentication() -> bool {
true
}
fn rate_limited() -> bool {
true
}
}
impl Display for ReceiptType {
fn fmt(&self, f: &mut Formatter) -> Result<(), FmtError> {
match *self {
ReceiptType::Read => write!(f, "m.read"),
}
}
}
}
|
Endpoint
|
identifier_name
|
receipt.rs
|
//! Endpoints for event receipts.
/// [POST /_matrix/client/r0/rooms/{roomId}/receipt/{receiptType}/{eventId}](https://matrix.org/docs/spec/client_server/r0.2.0.html#post-matrix-client-r0-rooms-roomid-receipt-receipttype-eventid)
pub mod create_receipt {
use ruma_identifiers::{EventId, RoomId};
use std::fmt::{Display, Error as FmtError, Formatter};
/// Details about this API endpoint.
#[derive(Clone, Copy, Debug)]
pub struct Endpoint;
/// This endpoint's path parameters.
#[derive(Clone, Debug)]
pub struct PathParams {
/// The event ID to acknowledge up to.
pub event_id: EventId,
/// The type of receipt to send.
pub receipt_type: ReceiptType,
/// The room in which to send the event.
pub room_id: RoomId,
}
/// The type of receipt.
#[derive(Clone, Copy, Debug)]
pub enum ReceiptType {
/// m.read
Read,
}
/// This API endpoint's response.
#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
pub struct Response;
impl<'de> ::Endpoint<'de> for Endpoint {
type BodyParams = ();
type PathParams = PathParams;
type QueryParams = ();
type Response = Response;
fn method() -> ::Method {
::Method::Post
}
fn request_path(params: Self::PathParams) -> String {
format!(
"/_matrix/client/r0/rooms/{}/receipt/{}/{}",
params.room_id,
params.receipt_type,
params.event_id
)
}
fn router_path() -> &'static str {
"/_matrix/client/r0/rooms/:room_id/receipt/:receipt_type/:event_id"
}
fn name() -> &'static str {
"create_receipt"
}
fn description() -> &'static str {
"Send a receipt event to a room."
}
fn requires_authentication() -> bool
|
fn rate_limited() -> bool {
true
}
}
impl Display for ReceiptType {
fn fmt(&self, f: &mut Formatter) -> Result<(), FmtError> {
match *self {
ReceiptType::Read => write!(f, "m.read"),
}
}
}
}
|
{
true
}
|
identifier_body
|
receipt.rs
|
//! Endpoints for event receipts.
/// [POST /_matrix/client/r0/rooms/{roomId}/receipt/{receiptType}/{eventId}](https://matrix.org/docs/spec/client_server/r0.2.0.html#post-matrix-client-r0-rooms-roomid-receipt-receipttype-eventid)
pub mod create_receipt {
use ruma_identifiers::{EventId, RoomId};
use std::fmt::{Display, Error as FmtError, Formatter};
/// Details about this API endpoint.
#[derive(Clone, Copy, Debug)]
pub struct Endpoint;
/// This endpoint's path parameters.
#[derive(Clone, Debug)]
pub struct PathParams {
/// The event ID to acknowledge up to.
pub event_id: EventId,
/// The type of receipt to send.
pub receipt_type: ReceiptType,
/// The room in which to send the event.
pub room_id: RoomId,
}
/// The type of receipt.
|
}
/// This API endpoint's response.
#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
pub struct Response;
impl<'de> ::Endpoint<'de> for Endpoint {
type BodyParams = ();
type PathParams = PathParams;
type QueryParams = ();
type Response = Response;
fn method() -> ::Method {
::Method::Post
}
fn request_path(params: Self::PathParams) -> String {
format!(
"/_matrix/client/r0/rooms/{}/receipt/{}/{}",
params.room_id,
params.receipt_type,
params.event_id
)
}
fn router_path() -> &'static str {
"/_matrix/client/r0/rooms/:room_id/receipt/:receipt_type/:event_id"
}
fn name() -> &'static str {
"create_receipt"
}
fn description() -> &'static str {
"Send a receipt event to a room."
}
fn requires_authentication() -> bool {
true
}
fn rate_limited() -> bool {
true
}
}
impl Display for ReceiptType {
fn fmt(&self, f: &mut Formatter) -> Result<(), FmtError> {
match *self {
ReceiptType::Read => write!(f, "m.read"),
}
}
}
}
|
#[derive(Clone, Copy, Debug)]
pub enum ReceiptType {
/// m.read
Read,
|
random_line_split
|
texturegl.rs
|
// Copyright (c) 2016-2018 Bruce Stenning. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
// OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
// AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
// THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
use std::ptr;
use std::mem;
use std::os::raw;
use std::any::Any;
use std::fmt;
use gl;
use gl::types::*;
use graphics::texture::*;
#[derive(Clone)]
pub struct TextureGl {
pub texture_name: GLuint,
}
impl TextureGl {
/// Construct a new texture
///
/// width: The width of the texture
/// height: The height of the texture
/// depth: true if the buffer should be depth, false if it should be colour
/// floating: true if the buffer should be floating point, false if it should be byte
/// msaa: The multisample factor
/// data: The image data, empty if just defining the texture not populating it
pub fn new(width: u32, height: u32, depth: bool, floating: bool, msaa: u32, data: &Vec<u8>) -> TextureGl {
let mut texture_name: GLuint = 0;
let internal_format = if depth { gl::DEPTH_COMPONENT } else { gl::RGBA };
let data_format = if depth { gl::DEPTH_COMPONENT } else { gl::RGBA };
let data_type = if floating {
gl::FLOAT
} else {
gl::UNSIGNED_BYTE
};
unsafe {
gl::PixelStorei(gl::UNPACK_ALIGNMENT, 1);
gl::GenTextures(1, &mut texture_name);
gl::BindTexture(
if msaa > 1 {
gl::TEXTURE_2D_MULTISAMPLE
} else {
gl::TEXTURE_2D
},
texture_name,
);
if msaa > 1 {
gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_WRAP_S, gl::REPEAT as GLint);
gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_WRAP_T, gl::REPEAT as GLint);
gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MAG_FILTER, gl::NEAREST as GLint);
gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MIN_FILTER, gl::NEAREST as GLint);
} else {
gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_WRAP_S, gl::REPEAT as GLint);
gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_WRAP_T, gl::REPEAT as GLint);
gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MAG_FILTER, gl::LINEAR as GLint);
gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MIN_FILTER, gl::LINEAR as GLint);
}
let mut ptr: *const raw::c_void = ptr::null();
if data.len()!= 0 {
ptr = mem::transmute(data.as_ptr());
};
if msaa > 1 {
gl::TexImage2DMultisample(
gl::TEXTURE_2D_MULTISAMPLE,
msaa as GLsizei,
internal_format as GLuint,
width as GLint,
height as GLint,
gl::FALSE, // Fixed sample locations
|
gl::TEXTURE_2D,
0, // Mipmap level
internal_format as GLint,
width as GLint,
height as GLint,
0, // Border: must be zero
data_format,
data_type,
ptr,
);
}
}
TextureGl { texture_name: texture_name }
}
}
impl Texture for TextureGl {
/// To facilitate downcasting back to a concrete type
fn as_any(&self) -> &Any {
self
}
fn as_any_mut(&mut self) -> &mut Any {
self
}
/// Bind the texture as the specified active texture number
///
/// num: The texture number to bind the texture to
fn bind(&self, num: i32) {
unsafe {
gl::ActiveTexture(match num {
1 => gl::TEXTURE1,
_ => gl::TEXTURE0,
});
gl::BindTexture(gl::TEXTURE_2D, self.texture_name);
}
}
}
// Output the handle associated with the textures's image, for debug purposes
impl fmt::Debug for TextureGl {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:08x}", self.texture_name)
}
}
|
);
} else {
gl::TexImage2D(
|
random_line_split
|
texturegl.rs
|
// Copyright (c) 2016-2018 Bruce Stenning. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
// OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
// AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
// THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
use std::ptr;
use std::mem;
use std::os::raw;
use std::any::Any;
use std::fmt;
use gl;
use gl::types::*;
use graphics::texture::*;
#[derive(Clone)]
pub struct TextureGl {
pub texture_name: GLuint,
}
impl TextureGl {
/// Construct a new texture
///
/// width: The width of the texture
/// height: The height of the texture
/// depth: true if the buffer should be depth, false if it should be colour
/// floating: true if the buffer should be floating point, false if it should be byte
/// msaa: The multisample factor
/// data: The image data, empty if just defining the texture not populating it
pub fn new(width: u32, height: u32, depth: bool, floating: bool, msaa: u32, data: &Vec<u8>) -> TextureGl {
let mut texture_name: GLuint = 0;
let internal_format = if depth { gl::DEPTH_COMPONENT } else { gl::RGBA };
let data_format = if depth { gl::DEPTH_COMPONENT } else { gl::RGBA };
let data_type = if floating {
gl::FLOAT
} else {
gl::UNSIGNED_BYTE
};
unsafe {
gl::PixelStorei(gl::UNPACK_ALIGNMENT, 1);
gl::GenTextures(1, &mut texture_name);
gl::BindTexture(
if msaa > 1 {
gl::TEXTURE_2D_MULTISAMPLE
} else {
gl::TEXTURE_2D
},
texture_name,
);
if msaa > 1 {
gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_WRAP_S, gl::REPEAT as GLint);
gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_WRAP_T, gl::REPEAT as GLint);
gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MAG_FILTER, gl::NEAREST as GLint);
gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MIN_FILTER, gl::NEAREST as GLint);
} else {
gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_WRAP_S, gl::REPEAT as GLint);
gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_WRAP_T, gl::REPEAT as GLint);
gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MAG_FILTER, gl::LINEAR as GLint);
gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MIN_FILTER, gl::LINEAR as GLint);
}
let mut ptr: *const raw::c_void = ptr::null();
if data.len()!= 0 {
ptr = mem::transmute(data.as_ptr());
};
if msaa > 1 {
gl::TexImage2DMultisample(
gl::TEXTURE_2D_MULTISAMPLE,
msaa as GLsizei,
internal_format as GLuint,
width as GLint,
height as GLint,
gl::FALSE, // Fixed sample locations
);
} else {
gl::TexImage2D(
gl::TEXTURE_2D,
0, // Mipmap level
internal_format as GLint,
width as GLint,
height as GLint,
0, // Border: must be zero
data_format,
data_type,
ptr,
);
}
}
TextureGl { texture_name: texture_name }
}
}
impl Texture for TextureGl {
/// To facilitate downcasting back to a concrete type
fn as_any(&self) -> &Any {
self
}
fn as_any_mut(&mut self) -> &mut Any {
self
}
/// Bind the texture as the specified active texture number
///
/// num: The texture number to bind the texture to
fn
|
(&self, num: i32) {
unsafe {
gl::ActiveTexture(match num {
1 => gl::TEXTURE1,
_ => gl::TEXTURE0,
});
gl::BindTexture(gl::TEXTURE_2D, self.texture_name);
}
}
}
// Output the handle associated with the textures's image, for debug purposes
impl fmt::Debug for TextureGl {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:08x}", self.texture_name)
}
}
|
bind
|
identifier_name
|
texturegl.rs
|
// Copyright (c) 2016-2018 Bruce Stenning. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
// OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
// AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
// THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
use std::ptr;
use std::mem;
use std::os::raw;
use std::any::Any;
use std::fmt;
use gl;
use gl::types::*;
use graphics::texture::*;
#[derive(Clone)]
pub struct TextureGl {
pub texture_name: GLuint,
}
impl TextureGl {
/// Construct a new texture
///
/// width: The width of the texture
/// height: The height of the texture
/// depth: true if the buffer should be depth, false if it should be colour
/// floating: true if the buffer should be floating point, false if it should be byte
/// msaa: The multisample factor
/// data: The image data, empty if just defining the texture not populating it
pub fn new(width: u32, height: u32, depth: bool, floating: bool, msaa: u32, data: &Vec<u8>) -> TextureGl {
let mut texture_name: GLuint = 0;
let internal_format = if depth { gl::DEPTH_COMPONENT } else { gl::RGBA };
let data_format = if depth { gl::DEPTH_COMPONENT } else { gl::RGBA };
let data_type = if floating {
gl::FLOAT
} else {
gl::UNSIGNED_BYTE
};
unsafe {
gl::PixelStorei(gl::UNPACK_ALIGNMENT, 1);
gl::GenTextures(1, &mut texture_name);
gl::BindTexture(
if msaa > 1 {
gl::TEXTURE_2D_MULTISAMPLE
} else {
gl::TEXTURE_2D
},
texture_name,
);
if msaa > 1 {
gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_WRAP_S, gl::REPEAT as GLint);
gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_WRAP_T, gl::REPEAT as GLint);
gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MAG_FILTER, gl::NEAREST as GLint);
gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MIN_FILTER, gl::NEAREST as GLint);
} else
|
let mut ptr: *const raw::c_void = ptr::null();
if data.len()!= 0 {
ptr = mem::transmute(data.as_ptr());
};
if msaa > 1 {
gl::TexImage2DMultisample(
gl::TEXTURE_2D_MULTISAMPLE,
msaa as GLsizei,
internal_format as GLuint,
width as GLint,
height as GLint,
gl::FALSE, // Fixed sample locations
);
} else {
gl::TexImage2D(
gl::TEXTURE_2D,
0, // Mipmap level
internal_format as GLint,
width as GLint,
height as GLint,
0, // Border: must be zero
data_format,
data_type,
ptr,
);
}
}
TextureGl { texture_name: texture_name }
}
}
impl Texture for TextureGl {
/// To facilitate downcasting back to a concrete type
fn as_any(&self) -> &Any {
self
}
fn as_any_mut(&mut self) -> &mut Any {
self
}
/// Bind the texture as the specified active texture number
///
/// num: The texture number to bind the texture to
fn bind(&self, num: i32) {
unsafe {
gl::ActiveTexture(match num {
1 => gl::TEXTURE1,
_ => gl::TEXTURE0,
});
gl::BindTexture(gl::TEXTURE_2D, self.texture_name);
}
}
}
// Output the handle associated with the textures's image, for debug purposes
impl fmt::Debug for TextureGl {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:08x}", self.texture_name)
}
}
|
{
gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_WRAP_S, gl::REPEAT as GLint);
gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_WRAP_T, gl::REPEAT as GLint);
gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MAG_FILTER, gl::LINEAR as GLint);
gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MIN_FILTER, gl::LINEAR as GLint);
}
|
conditional_block
|
texturegl.rs
|
// Copyright (c) 2016-2018 Bruce Stenning. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
// OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
// AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
// THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
use std::ptr;
use std::mem;
use std::os::raw;
use std::any::Any;
use std::fmt;
use gl;
use gl::types::*;
use graphics::texture::*;
#[derive(Clone)]
pub struct TextureGl {
pub texture_name: GLuint,
}
impl TextureGl {
/// Construct a new texture
///
/// width: The width of the texture
/// height: The height of the texture
/// depth: true if the buffer should be depth, false if it should be colour
/// floating: true if the buffer should be floating point, false if it should be byte
/// msaa: The multisample factor
/// data: The image data, empty if just defining the texture not populating it
pub fn new(width: u32, height: u32, depth: bool, floating: bool, msaa: u32, data: &Vec<u8>) -> TextureGl
|
},
texture_name,
);
if msaa > 1 {
gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_WRAP_S, gl::REPEAT as GLint);
gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_WRAP_T, gl::REPEAT as GLint);
gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MAG_FILTER, gl::NEAREST as GLint);
gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MIN_FILTER, gl::NEAREST as GLint);
} else {
gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_WRAP_S, gl::REPEAT as GLint);
gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_WRAP_T, gl::REPEAT as GLint);
gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MAG_FILTER, gl::LINEAR as GLint);
gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MIN_FILTER, gl::LINEAR as GLint);
}
let mut ptr: *const raw::c_void = ptr::null();
if data.len()!= 0 {
ptr = mem::transmute(data.as_ptr());
};
if msaa > 1 {
gl::TexImage2DMultisample(
gl::TEXTURE_2D_MULTISAMPLE,
msaa as GLsizei,
internal_format as GLuint,
width as GLint,
height as GLint,
gl::FALSE, // Fixed sample locations
);
} else {
gl::TexImage2D(
gl::TEXTURE_2D,
0, // Mipmap level
internal_format as GLint,
width as GLint,
height as GLint,
0, // Border: must be zero
data_format,
data_type,
ptr,
);
}
}
TextureGl { texture_name: texture_name }
}
}
impl Texture for TextureGl {
/// To facilitate downcasting back to a concrete type
fn as_any(&self) -> &Any {
self
}
fn as_any_mut(&mut self) -> &mut Any {
self
}
/// Bind the texture as the specified active texture number
///
/// num: The texture number to bind the texture to
fn bind(&self, num: i32) {
unsafe {
gl::ActiveTexture(match num {
1 => gl::TEXTURE1,
_ => gl::TEXTURE0,
});
gl::BindTexture(gl::TEXTURE_2D, self.texture_name);
}
}
}
// Output the handle associated with the textures's image, for debug purposes
impl fmt::Debug for TextureGl {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:08x}", self.texture_name)
}
}
|
{
let mut texture_name: GLuint = 0;
let internal_format = if depth { gl::DEPTH_COMPONENT } else { gl::RGBA };
let data_format = if depth { gl::DEPTH_COMPONENT } else { gl::RGBA };
let data_type = if floating {
gl::FLOAT
} else {
gl::UNSIGNED_BYTE
};
unsafe {
gl::PixelStorei(gl::UNPACK_ALIGNMENT, 1);
gl::GenTextures(1, &mut texture_name);
gl::BindTexture(
if msaa > 1 {
gl::TEXTURE_2D_MULTISAMPLE
} else {
gl::TEXTURE_2D
|
identifier_body
|
animation.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 transitions and animations.
use context::SharedLayoutContext;
use flow::{self, Flow};
use gfx::display_list::OpaqueNode;
use ipc_channel::ipc::IpcSender;
use msg::constellation_msg::PipelineId;
use script_traits::{AnimationState, ConstellationControlMsg, LayoutMsg as ConstellationMsg};
use std::collections::HashMap;
use std::sync::mpsc::Receiver;
use style::animation::{Animation, update_style_for_animation};
use style::selector_parser::RestyleDamage;
use style::timer::Timer;
/// Processes any new animations that were discovered after style recalculation.
/// Also expire any old animations that have completed, inserting them into
/// `expired_animations`.
pub fn update_animation_state(constellation_chan: &IpcSender<ConstellationMsg>,
script_chan: &IpcSender<ConstellationControlMsg>,
running_animations: &mut HashMap<OpaqueNode, Vec<Animation>>,
expired_animations: &mut HashMap<OpaqueNode, Vec<Animation>>,
new_animations_receiver: &Receiver<Animation>,
pipeline_id: PipelineId,
timer: &Timer) {
let mut new_running_animations = vec![];
while let Ok(animation) = new_animations_receiver.try_recv() {
let mut should_push = true;
if let Animation::Keyframes(ref node, ref name, ref state) = animation {
// If the animation was already present in the list for the
// node, just update its state, else push the new animation to
// run.
if let Some(ref mut animations) = running_animations.get_mut(node) {
// TODO: This being linear is probably not optimal.
for mut anim in animations.iter_mut() {
if let Animation::Keyframes(_, ref anim_name, ref mut anim_state) = *anim {
if *name == *anim_name {
debug!("update_animation_state: Found other animation {}", name);
anim_state.update_from_other(&state, timer);
should_push = false;
break;
}
}
}
}
}
if should_push {
new_running_animations.push(animation);
}
}
if running_animations.is_empty() && new_running_animations.is_empty() {
// Nothing to do. Return early so we don't flood the compositor with
// `ChangeRunningAnimationsState` messages.
return
}
let now = timer.seconds();
// Expire old running animations.
//
// TODO: Do not expunge Keyframes animations, since we need that state if
// the animation gets re-triggered. Probably worth splitting in two
// different maps, or at least using a linked list?
let mut keys_to_remove = vec![];
for (key, running_animations) in running_animations.iter_mut() {
let mut animations_still_running = vec![];
for mut running_animation in running_animations.drain(..) {
let still_running =!running_animation.is_expired() && match running_animation {
|
Animation::Keyframes(_, _, ref mut state) => {
// This animation is still running, or we need to keep
// iterating.
now < state.started_at + state.duration || state.tick()
}
};
if still_running {
animations_still_running.push(running_animation);
continue
}
if let Animation::Transition(_, unsafe_node, _, ref frame, _) = running_animation {
script_chan.send(ConstellationControlMsg::TransitionEnd(unsafe_node,
frame.property_animation
.property_name().into(),
frame.duration))
.unwrap();
}
expired_animations.entry(*key)
.or_insert_with(Vec::new)
.push(running_animation);
}
if animations_still_running.is_empty() {
keys_to_remove.push(*key);
} else {
*running_animations = animations_still_running
}
}
for key in keys_to_remove {
running_animations.remove(&key).unwrap();
}
// Add new running animations.
for new_running_animation in new_running_animations {
running_animations.entry(*new_running_animation.node())
.or_insert_with(Vec::new)
.push(new_running_animation)
}
let animation_state = if running_animations.is_empty() {
AnimationState::NoAnimationsPresent
} else {
AnimationState::AnimationsPresent
};
constellation_chan.send(ConstellationMsg::ChangeRunningAnimationsState(pipeline_id,
animation_state))
.unwrap();
}
/// Recalculates style for a set of animations. This does *not* run with the DOM
/// lock held.
// NB: This is specific for SelectorImpl, since the layout context and the
// flows are SelectorImpl specific too. If that goes away at some point,
// this should be made generic.
pub fn recalc_style_for_animations(context: &SharedLayoutContext,
flow: &mut Flow,
animations: &HashMap<OpaqueNode,
Vec<Animation>>) {
let mut damage = RestyleDamage::empty();
flow.mutate_fragments(&mut |fragment| {
if let Some(ref animations) = animations.get(&fragment.node) {
for animation in animations.iter() {
let old_style = fragment.style.clone();
update_style_for_animation(&context.style_context,
animation,
&mut fragment.style);
damage |= RestyleDamage::compute(&old_style, &fragment.style);
}
}
});
let base = flow::mut_base(flow);
base.restyle_damage.insert(damage);
for kid in base.children.iter_mut() {
recalc_style_for_animations(context, kid, animations)
}
}
|
Animation::Transition(_, _, started_at, ref frame, _expired) => {
now < started_at + frame.duration
}
|
random_line_split
|
animation.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 transitions and animations.
use context::SharedLayoutContext;
use flow::{self, Flow};
use gfx::display_list::OpaqueNode;
use ipc_channel::ipc::IpcSender;
use msg::constellation_msg::PipelineId;
use script_traits::{AnimationState, ConstellationControlMsg, LayoutMsg as ConstellationMsg};
use std::collections::HashMap;
use std::sync::mpsc::Receiver;
use style::animation::{Animation, update_style_for_animation};
use style::selector_parser::RestyleDamage;
use style::timer::Timer;
/// Processes any new animations that were discovered after style recalculation.
/// Also expire any old animations that have completed, inserting them into
/// `expired_animations`.
pub fn update_animation_state(constellation_chan: &IpcSender<ConstellationMsg>,
script_chan: &IpcSender<ConstellationControlMsg>,
running_animations: &mut HashMap<OpaqueNode, Vec<Animation>>,
expired_animations: &mut HashMap<OpaqueNode, Vec<Animation>>,
new_animations_receiver: &Receiver<Animation>,
pipeline_id: PipelineId,
timer: &Timer) {
let mut new_running_animations = vec![];
while let Ok(animation) = new_animations_receiver.try_recv() {
let mut should_push = true;
if let Animation::Keyframes(ref node, ref name, ref state) = animation {
// If the animation was already present in the list for the
// node, just update its state, else push the new animation to
// run.
if let Some(ref mut animations) = running_animations.get_mut(node) {
// TODO: This being linear is probably not optimal.
for mut anim in animations.iter_mut() {
if let Animation::Keyframes(_, ref anim_name, ref mut anim_state) = *anim {
if *name == *anim_name {
debug!("update_animation_state: Found other animation {}", name);
anim_state.update_from_other(&state, timer);
should_push = false;
break;
}
}
}
}
}
if should_push {
new_running_animations.push(animation);
}
}
if running_animations.is_empty() && new_running_animations.is_empty() {
// Nothing to do. Return early so we don't flood the compositor with
// `ChangeRunningAnimationsState` messages.
return
}
let now = timer.seconds();
// Expire old running animations.
//
// TODO: Do not expunge Keyframes animations, since we need that state if
// the animation gets re-triggered. Probably worth splitting in two
// different maps, or at least using a linked list?
let mut keys_to_remove = vec![];
for (key, running_animations) in running_animations.iter_mut() {
let mut animations_still_running = vec![];
for mut running_animation in running_animations.drain(..) {
let still_running =!running_animation.is_expired() && match running_animation {
Animation::Transition(_, _, started_at, ref frame, _expired) => {
now < started_at + frame.duration
}
Animation::Keyframes(_, _, ref mut state) => {
// This animation is still running, or we need to keep
// iterating.
now < state.started_at + state.duration || state.tick()
}
};
if still_running {
animations_still_running.push(running_animation);
continue
}
if let Animation::Transition(_, unsafe_node, _, ref frame, _) = running_animation {
script_chan.send(ConstellationControlMsg::TransitionEnd(unsafe_node,
frame.property_animation
.property_name().into(),
frame.duration))
.unwrap();
}
expired_animations.entry(*key)
.or_insert_with(Vec::new)
.push(running_animation);
}
if animations_still_running.is_empty() {
keys_to_remove.push(*key);
} else {
*running_animations = animations_still_running
}
}
for key in keys_to_remove {
running_animations.remove(&key).unwrap();
}
// Add new running animations.
for new_running_animation in new_running_animations {
running_animations.entry(*new_running_animation.node())
.or_insert_with(Vec::new)
.push(new_running_animation)
}
let animation_state = if running_animations.is_empty() {
AnimationState::NoAnimationsPresent
} else {
AnimationState::AnimationsPresent
};
constellation_chan.send(ConstellationMsg::ChangeRunningAnimationsState(pipeline_id,
animation_state))
.unwrap();
}
/// Recalculates style for a set of animations. This does *not* run with the DOM
/// lock held.
// NB: This is specific for SelectorImpl, since the layout context and the
// flows are SelectorImpl specific too. If that goes away at some point,
// this should be made generic.
pub fn recalc_style_for_animations(context: &SharedLayoutContext,
flow: &mut Flow,
animations: &HashMap<OpaqueNode,
Vec<Animation>>)
|
{
let mut damage = RestyleDamage::empty();
flow.mutate_fragments(&mut |fragment| {
if let Some(ref animations) = animations.get(&fragment.node) {
for animation in animations.iter() {
let old_style = fragment.style.clone();
update_style_for_animation(&context.style_context,
animation,
&mut fragment.style);
damage |= RestyleDamage::compute(&old_style, &fragment.style);
}
}
});
let base = flow::mut_base(flow);
base.restyle_damage.insert(damage);
for kid in base.children.iter_mut() {
recalc_style_for_animations(context, kid, animations)
}
}
|
identifier_body
|
|
animation.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 transitions and animations.
use context::SharedLayoutContext;
use flow::{self, Flow};
use gfx::display_list::OpaqueNode;
use ipc_channel::ipc::IpcSender;
use msg::constellation_msg::PipelineId;
use script_traits::{AnimationState, ConstellationControlMsg, LayoutMsg as ConstellationMsg};
use std::collections::HashMap;
use std::sync::mpsc::Receiver;
use style::animation::{Animation, update_style_for_animation};
use style::selector_parser::RestyleDamage;
use style::timer::Timer;
/// Processes any new animations that were discovered after style recalculation.
/// Also expire any old animations that have completed, inserting them into
/// `expired_animations`.
pub fn update_animation_state(constellation_chan: &IpcSender<ConstellationMsg>,
script_chan: &IpcSender<ConstellationControlMsg>,
running_animations: &mut HashMap<OpaqueNode, Vec<Animation>>,
expired_animations: &mut HashMap<OpaqueNode, Vec<Animation>>,
new_animations_receiver: &Receiver<Animation>,
pipeline_id: PipelineId,
timer: &Timer) {
let mut new_running_animations = vec![];
while let Ok(animation) = new_animations_receiver.try_recv() {
let mut should_push = true;
if let Animation::Keyframes(ref node, ref name, ref state) = animation
|
if should_push {
new_running_animations.push(animation);
}
}
if running_animations.is_empty() && new_running_animations.is_empty() {
// Nothing to do. Return early so we don't flood the compositor with
// `ChangeRunningAnimationsState` messages.
return
}
let now = timer.seconds();
// Expire old running animations.
//
// TODO: Do not expunge Keyframes animations, since we need that state if
// the animation gets re-triggered. Probably worth splitting in two
// different maps, or at least using a linked list?
let mut keys_to_remove = vec![];
for (key, running_animations) in running_animations.iter_mut() {
let mut animations_still_running = vec![];
for mut running_animation in running_animations.drain(..) {
let still_running =!running_animation.is_expired() && match running_animation {
Animation::Transition(_, _, started_at, ref frame, _expired) => {
now < started_at + frame.duration
}
Animation::Keyframes(_, _, ref mut state) => {
// This animation is still running, or we need to keep
// iterating.
now < state.started_at + state.duration || state.tick()
}
};
if still_running {
animations_still_running.push(running_animation);
continue
}
if let Animation::Transition(_, unsafe_node, _, ref frame, _) = running_animation {
script_chan.send(ConstellationControlMsg::TransitionEnd(unsafe_node,
frame.property_animation
.property_name().into(),
frame.duration))
.unwrap();
}
expired_animations.entry(*key)
.or_insert_with(Vec::new)
.push(running_animation);
}
if animations_still_running.is_empty() {
keys_to_remove.push(*key);
} else {
*running_animations = animations_still_running
}
}
for key in keys_to_remove {
running_animations.remove(&key).unwrap();
}
// Add new running animations.
for new_running_animation in new_running_animations {
running_animations.entry(*new_running_animation.node())
.or_insert_with(Vec::new)
.push(new_running_animation)
}
let animation_state = if running_animations.is_empty() {
AnimationState::NoAnimationsPresent
} else {
AnimationState::AnimationsPresent
};
constellation_chan.send(ConstellationMsg::ChangeRunningAnimationsState(pipeline_id,
animation_state))
.unwrap();
}
/// Recalculates style for a set of animations. This does *not* run with the DOM
/// lock held.
// NB: This is specific for SelectorImpl, since the layout context and the
// flows are SelectorImpl specific too. If that goes away at some point,
// this should be made generic.
pub fn recalc_style_for_animations(context: &SharedLayoutContext,
flow: &mut Flow,
animations: &HashMap<OpaqueNode,
Vec<Animation>>) {
let mut damage = RestyleDamage::empty();
flow.mutate_fragments(&mut |fragment| {
if let Some(ref animations) = animations.get(&fragment.node) {
for animation in animations.iter() {
let old_style = fragment.style.clone();
update_style_for_animation(&context.style_context,
animation,
&mut fragment.style);
damage |= RestyleDamage::compute(&old_style, &fragment.style);
}
}
});
let base = flow::mut_base(flow);
base.restyle_damage.insert(damage);
for kid in base.children.iter_mut() {
recalc_style_for_animations(context, kid, animations)
}
}
|
{
// If the animation was already present in the list for the
// node, just update its state, else push the new animation to
// run.
if let Some(ref mut animations) = running_animations.get_mut(node) {
// TODO: This being linear is probably not optimal.
for mut anim in animations.iter_mut() {
if let Animation::Keyframes(_, ref anim_name, ref mut anim_state) = *anim {
if *name == *anim_name {
debug!("update_animation_state: Found other animation {}", name);
anim_state.update_from_other(&state, timer);
should_push = false;
break;
}
}
}
}
}
|
conditional_block
|
animation.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 transitions and animations.
use context::SharedLayoutContext;
use flow::{self, Flow};
use gfx::display_list::OpaqueNode;
use ipc_channel::ipc::IpcSender;
use msg::constellation_msg::PipelineId;
use script_traits::{AnimationState, ConstellationControlMsg, LayoutMsg as ConstellationMsg};
use std::collections::HashMap;
use std::sync::mpsc::Receiver;
use style::animation::{Animation, update_style_for_animation};
use style::selector_parser::RestyleDamage;
use style::timer::Timer;
/// Processes any new animations that were discovered after style recalculation.
/// Also expire any old animations that have completed, inserting them into
/// `expired_animations`.
pub fn update_animation_state(constellation_chan: &IpcSender<ConstellationMsg>,
script_chan: &IpcSender<ConstellationControlMsg>,
running_animations: &mut HashMap<OpaqueNode, Vec<Animation>>,
expired_animations: &mut HashMap<OpaqueNode, Vec<Animation>>,
new_animations_receiver: &Receiver<Animation>,
pipeline_id: PipelineId,
timer: &Timer) {
let mut new_running_animations = vec![];
while let Ok(animation) = new_animations_receiver.try_recv() {
let mut should_push = true;
if let Animation::Keyframes(ref node, ref name, ref state) = animation {
// If the animation was already present in the list for the
// node, just update its state, else push the new animation to
// run.
if let Some(ref mut animations) = running_animations.get_mut(node) {
// TODO: This being linear is probably not optimal.
for mut anim in animations.iter_mut() {
if let Animation::Keyframes(_, ref anim_name, ref mut anim_state) = *anim {
if *name == *anim_name {
debug!("update_animation_state: Found other animation {}", name);
anim_state.update_from_other(&state, timer);
should_push = false;
break;
}
}
}
}
}
if should_push {
new_running_animations.push(animation);
}
}
if running_animations.is_empty() && new_running_animations.is_empty() {
// Nothing to do. Return early so we don't flood the compositor with
// `ChangeRunningAnimationsState` messages.
return
}
let now = timer.seconds();
// Expire old running animations.
//
// TODO: Do not expunge Keyframes animations, since we need that state if
// the animation gets re-triggered. Probably worth splitting in two
// different maps, or at least using a linked list?
let mut keys_to_remove = vec![];
for (key, running_animations) in running_animations.iter_mut() {
let mut animations_still_running = vec![];
for mut running_animation in running_animations.drain(..) {
let still_running =!running_animation.is_expired() && match running_animation {
Animation::Transition(_, _, started_at, ref frame, _expired) => {
now < started_at + frame.duration
}
Animation::Keyframes(_, _, ref mut state) => {
// This animation is still running, or we need to keep
// iterating.
now < state.started_at + state.duration || state.tick()
}
};
if still_running {
animations_still_running.push(running_animation);
continue
}
if let Animation::Transition(_, unsafe_node, _, ref frame, _) = running_animation {
script_chan.send(ConstellationControlMsg::TransitionEnd(unsafe_node,
frame.property_animation
.property_name().into(),
frame.duration))
.unwrap();
}
expired_animations.entry(*key)
.or_insert_with(Vec::new)
.push(running_animation);
}
if animations_still_running.is_empty() {
keys_to_remove.push(*key);
} else {
*running_animations = animations_still_running
}
}
for key in keys_to_remove {
running_animations.remove(&key).unwrap();
}
// Add new running animations.
for new_running_animation in new_running_animations {
running_animations.entry(*new_running_animation.node())
.or_insert_with(Vec::new)
.push(new_running_animation)
}
let animation_state = if running_animations.is_empty() {
AnimationState::NoAnimationsPresent
} else {
AnimationState::AnimationsPresent
};
constellation_chan.send(ConstellationMsg::ChangeRunningAnimationsState(pipeline_id,
animation_state))
.unwrap();
}
/// Recalculates style for a set of animations. This does *not* run with the DOM
/// lock held.
// NB: This is specific for SelectorImpl, since the layout context and the
// flows are SelectorImpl specific too. If that goes away at some point,
// this should be made generic.
pub fn
|
(context: &SharedLayoutContext,
flow: &mut Flow,
animations: &HashMap<OpaqueNode,
Vec<Animation>>) {
let mut damage = RestyleDamage::empty();
flow.mutate_fragments(&mut |fragment| {
if let Some(ref animations) = animations.get(&fragment.node) {
for animation in animations.iter() {
let old_style = fragment.style.clone();
update_style_for_animation(&context.style_context,
animation,
&mut fragment.style);
damage |= RestyleDamage::compute(&old_style, &fragment.style);
}
}
});
let base = flow::mut_base(flow);
base.restyle_damage.insert(damage);
for kid in base.children.iter_mut() {
recalc_style_for_animations(context, kid, animations)
}
}
|
recalc_style_for_animations
|
identifier_name
|
flatten.rs
|
use {Task, Poll};
use stream::Stream;
/// A combinator used to flatten a stream-of-streams into one long stream of
/// elements.
///
/// This combinator is created by the `Stream::flatten` method.
pub struct Flatten<S>
where S: Stream,
{
stream: S,
next: Option<S::Item>,
}
pub fn new<S>(s: S) -> Flatten<S>
where S: Stream,
S::Item: Stream,
<S::Item as Stream>::Error: From<S::Error>,
|
{
Flatten {
stream: s,
next: None,
}
}
impl<S> Stream for Flatten<S>
where S: Stream,
S::Item: Stream,
<S::Item as Stream>::Error: From<S::Error>,
{
type Item = <S::Item as Stream>::Item;
type Error = <S::Item as Stream>::Error;
fn poll(&mut self, task: &mut Task)
-> Poll<Option<Self::Item>, Self::Error> {
loop {
if self.next.is_none() {
match try_poll!(self.stream.poll(task)) {
Ok(Some(e)) => self.next = Some(e),
Ok(None) => return Poll::Ok(None),
Err(e) => return Poll::Err(From::from(e)),
}
}
assert!(self.next.is_some());
match self.next.as_mut().unwrap().poll(task) {
Poll::Ok(None) => self.next = None,
other => return other,
}
}
}
fn schedule(&mut self, task: &mut Task) {
match self.next {
Some(ref mut s) => s.schedule(task),
None => self.stream.schedule(task),
}
}
}
|
random_line_split
|
|
flatten.rs
|
use {Task, Poll};
use stream::Stream;
/// A combinator used to flatten a stream-of-streams into one long stream of
/// elements.
///
/// This combinator is created by the `Stream::flatten` method.
pub struct Flatten<S>
where S: Stream,
{
stream: S,
next: Option<S::Item>,
}
pub fn new<S>(s: S) -> Flatten<S>
where S: Stream,
S::Item: Stream,
<S::Item as Stream>::Error: From<S::Error>,
{
Flatten {
stream: s,
next: None,
}
}
impl<S> Stream for Flatten<S>
where S: Stream,
S::Item: Stream,
<S::Item as Stream>::Error: From<S::Error>,
{
type Item = <S::Item as Stream>::Item;
type Error = <S::Item as Stream>::Error;
fn poll(&mut self, task: &mut Task)
-> Poll<Option<Self::Item>, Self::Error> {
loop {
if self.next.is_none() {
match try_poll!(self.stream.poll(task)) {
Ok(Some(e)) => self.next = Some(e),
Ok(None) => return Poll::Ok(None),
Err(e) => return Poll::Err(From::from(e)),
}
}
assert!(self.next.is_some());
match self.next.as_mut().unwrap().poll(task) {
Poll::Ok(None) => self.next = None,
other => return other,
}
}
}
fn schedule(&mut self, task: &mut Task)
|
}
|
{
match self.next {
Some(ref mut s) => s.schedule(task),
None => self.stream.schedule(task),
}
}
|
identifier_body
|
flatten.rs
|
use {Task, Poll};
use stream::Stream;
/// A combinator used to flatten a stream-of-streams into one long stream of
/// elements.
///
/// This combinator is created by the `Stream::flatten` method.
pub struct Flatten<S>
where S: Stream,
{
stream: S,
next: Option<S::Item>,
}
pub fn new<S>(s: S) -> Flatten<S>
where S: Stream,
S::Item: Stream,
<S::Item as Stream>::Error: From<S::Error>,
{
Flatten {
stream: s,
next: None,
}
}
impl<S> Stream for Flatten<S>
where S: Stream,
S::Item: Stream,
<S::Item as Stream>::Error: From<S::Error>,
{
type Item = <S::Item as Stream>::Item;
type Error = <S::Item as Stream>::Error;
fn
|
(&mut self, task: &mut Task)
-> Poll<Option<Self::Item>, Self::Error> {
loop {
if self.next.is_none() {
match try_poll!(self.stream.poll(task)) {
Ok(Some(e)) => self.next = Some(e),
Ok(None) => return Poll::Ok(None),
Err(e) => return Poll::Err(From::from(e)),
}
}
assert!(self.next.is_some());
match self.next.as_mut().unwrap().poll(task) {
Poll::Ok(None) => self.next = None,
other => return other,
}
}
}
fn schedule(&mut self, task: &mut Task) {
match self.next {
Some(ref mut s) => s.schedule(task),
None => self.stream.schedule(task),
}
}
}
|
poll
|
identifier_name
|
unnecessary_sort_by.rs
|
// run-rustfix
#![allow(clippy::stable_sort_primitive)]
use std::cmp::Reverse;
fn unnecessary_sort_by() {
fn id(x: isize) -> isize {
x
}
let mut vec: Vec<isize> = vec![3, 6, 1, 2, 5];
// Forward examples
vec.sort_by(|a, b| a.cmp(b));
vec.sort_unstable_by(|a, b| a.cmp(b));
vec.sort_by(|a, b| (a + 5).abs().cmp(&(b + 5).abs()));
vec.sort_unstable_by(|a, b| id(-a).cmp(&id(-b)));
// Reverse examples
vec.sort_by(|a, b| b.cmp(a)); // not linted to avoid suggesting `Reverse(b)` which would borrow
vec.sort_by(|a, b| (b + 5).abs().cmp(&(a + 5).abs()));
vec.sort_unstable_by(|a, b| id(-b).cmp(&id(-a)));
// Negative examples (shouldn't be changed)
let c = &7;
vec.sort_by(|a, b| (b - a).cmp(&(a - b)));
vec.sort_by(|_, b| b.cmp(&5));
vec.sort_by(|_, b| b.cmp(c));
vec.sort_unstable_by(|a, _| a.cmp(c));
// Vectors of references are fine as long as the resulting key does not borrow
let mut vec: Vec<&&&isize> = vec![&&&3, &&&6, &&&1, &&&2, &&&5];
vec.sort_by(|a, b| (***a).abs().cmp(&(***b).abs()));
vec.sort_unstable_by(|a, b| (***a).abs().cmp(&(***b).abs()));
// `Reverse(b)` would borrow in the following cases, don't lint
vec.sort_by(|a, b| b.cmp(a));
vec.sort_unstable_by(|a, b| b.cmp(a));
}
// Do not suggest returning a reference to the closure parameter of `Vec::sort_by_key`
mod issue_5754 {
#[derive(Clone, Copy)]
struct Test(usize);
#[derive(PartialOrd, Ord, PartialEq, Eq)]
|
}
fn wrapped(&self) -> Wrapper<'_> {
Wrapper(&self.0)
}
}
pub fn test() {
let mut args: Vec<Test> = vec![];
// Forward
args.sort_by(|a, b| a.name().cmp(b.name()));
args.sort_by(|a, b| a.wrapped().cmp(&b.wrapped()));
args.sort_unstable_by(|a, b| a.name().cmp(b.name()));
args.sort_unstable_by(|a, b| a.wrapped().cmp(&b.wrapped()));
// Reverse
args.sort_by(|a, b| b.name().cmp(a.name()));
args.sort_by(|a, b| b.wrapped().cmp(&a.wrapped()));
args.sort_unstable_by(|a, b| b.name().cmp(a.name()));
args.sort_unstable_by(|a, b| b.wrapped().cmp(&a.wrapped()));
}
}
// The closure parameter is not dereferenced anymore, so non-Copy types can be linted
mod issue_6001 {
use super::*;
struct Test(String);
impl Test {
// Return an owned type so that we don't hit the fix for 5754
fn name(&self) -> String {
self.0.clone()
}
}
pub fn test() {
let mut args: Vec<Test> = vec![];
// Forward
args.sort_by(|a, b| a.name().cmp(&b.name()));
args.sort_unstable_by(|a, b| a.name().cmp(&b.name()));
// Reverse
args.sort_by(|a, b| b.name().cmp(&a.name()));
args.sort_unstable_by(|a, b| b.name().cmp(&a.name()));
}
}
fn main() {
unnecessary_sort_by();
issue_5754::test();
issue_6001::test();
}
|
struct Wrapper<'a>(&'a usize);
impl Test {
fn name(&self) -> &usize {
&self.0
|
random_line_split
|
unnecessary_sort_by.rs
|
// run-rustfix
#![allow(clippy::stable_sort_primitive)]
use std::cmp::Reverse;
fn unnecessary_sort_by()
|
vec.sort_unstable_by(|a, _| a.cmp(c));
// Vectors of references are fine as long as the resulting key does not borrow
let mut vec: Vec<&&&isize> = vec![&&&3, &&&6, &&&1, &&&2, &&&5];
vec.sort_by(|a, b| (***a).abs().cmp(&(***b).abs()));
vec.sort_unstable_by(|a, b| (***a).abs().cmp(&(***b).abs()));
// `Reverse(b)` would borrow in the following cases, don't lint
vec.sort_by(|a, b| b.cmp(a));
vec.sort_unstable_by(|a, b| b.cmp(a));
}
// Do not suggest returning a reference to the closure parameter of `Vec::sort_by_key`
mod issue_5754 {
#[derive(Clone, Copy)]
struct Test(usize);
#[derive(PartialOrd, Ord, PartialEq, Eq)]
struct Wrapper<'a>(&'a usize);
impl Test {
fn name(&self) -> &usize {
&self.0
}
fn wrapped(&self) -> Wrapper<'_> {
Wrapper(&self.0)
}
}
pub fn test() {
let mut args: Vec<Test> = vec![];
// Forward
args.sort_by(|a, b| a.name().cmp(b.name()));
args.sort_by(|a, b| a.wrapped().cmp(&b.wrapped()));
args.sort_unstable_by(|a, b| a.name().cmp(b.name()));
args.sort_unstable_by(|a, b| a.wrapped().cmp(&b.wrapped()));
// Reverse
args.sort_by(|a, b| b.name().cmp(a.name()));
args.sort_by(|a, b| b.wrapped().cmp(&a.wrapped()));
args.sort_unstable_by(|a, b| b.name().cmp(a.name()));
args.sort_unstable_by(|a, b| b.wrapped().cmp(&a.wrapped()));
}
}
// The closure parameter is not dereferenced anymore, so non-Copy types can be linted
mod issue_6001 {
use super::*;
struct Test(String);
impl Test {
// Return an owned type so that we don't hit the fix for 5754
fn name(&self) -> String {
self.0.clone()
}
}
pub fn test() {
let mut args: Vec<Test> = vec![];
// Forward
args.sort_by(|a, b| a.name().cmp(&b.name()));
args.sort_unstable_by(|a, b| a.name().cmp(&b.name()));
// Reverse
args.sort_by(|a, b| b.name().cmp(&a.name()));
args.sort_unstable_by(|a, b| b.name().cmp(&a.name()));
}
}
fn main() {
unnecessary_sort_by();
issue_5754::test();
issue_6001::test();
}
|
{
fn id(x: isize) -> isize {
x
}
let mut vec: Vec<isize> = vec![3, 6, 1, 2, 5];
// Forward examples
vec.sort_by(|a, b| a.cmp(b));
vec.sort_unstable_by(|a, b| a.cmp(b));
vec.sort_by(|a, b| (a + 5).abs().cmp(&(b + 5).abs()));
vec.sort_unstable_by(|a, b| id(-a).cmp(&id(-b)));
// Reverse examples
vec.sort_by(|a, b| b.cmp(a)); // not linted to avoid suggesting `Reverse(b)` which would borrow
vec.sort_by(|a, b| (b + 5).abs().cmp(&(a + 5).abs()));
vec.sort_unstable_by(|a, b| id(-b).cmp(&id(-a)));
// Negative examples (shouldn't be changed)
let c = &7;
vec.sort_by(|a, b| (b - a).cmp(&(a - b)));
vec.sort_by(|_, b| b.cmp(&5));
vec.sort_by(|_, b| b.cmp(c));
|
identifier_body
|
unnecessary_sort_by.rs
|
// run-rustfix
#![allow(clippy::stable_sort_primitive)]
use std::cmp::Reverse;
fn unnecessary_sort_by() {
fn id(x: isize) -> isize {
x
}
let mut vec: Vec<isize> = vec![3, 6, 1, 2, 5];
// Forward examples
vec.sort_by(|a, b| a.cmp(b));
vec.sort_unstable_by(|a, b| a.cmp(b));
vec.sort_by(|a, b| (a + 5).abs().cmp(&(b + 5).abs()));
vec.sort_unstable_by(|a, b| id(-a).cmp(&id(-b)));
// Reverse examples
vec.sort_by(|a, b| b.cmp(a)); // not linted to avoid suggesting `Reverse(b)` which would borrow
vec.sort_by(|a, b| (b + 5).abs().cmp(&(a + 5).abs()));
vec.sort_unstable_by(|a, b| id(-b).cmp(&id(-a)));
// Negative examples (shouldn't be changed)
let c = &7;
vec.sort_by(|a, b| (b - a).cmp(&(a - b)));
vec.sort_by(|_, b| b.cmp(&5));
vec.sort_by(|_, b| b.cmp(c));
vec.sort_unstable_by(|a, _| a.cmp(c));
// Vectors of references are fine as long as the resulting key does not borrow
let mut vec: Vec<&&&isize> = vec![&&&3, &&&6, &&&1, &&&2, &&&5];
vec.sort_by(|a, b| (***a).abs().cmp(&(***b).abs()));
vec.sort_unstable_by(|a, b| (***a).abs().cmp(&(***b).abs()));
// `Reverse(b)` would borrow in the following cases, don't lint
vec.sort_by(|a, b| b.cmp(a));
vec.sort_unstable_by(|a, b| b.cmp(a));
}
// Do not suggest returning a reference to the closure parameter of `Vec::sort_by_key`
mod issue_5754 {
#[derive(Clone, Copy)]
struct Test(usize);
#[derive(PartialOrd, Ord, PartialEq, Eq)]
struct Wrapper<'a>(&'a usize);
impl Test {
fn name(&self) -> &usize {
&self.0
}
fn wrapped(&self) -> Wrapper<'_> {
Wrapper(&self.0)
}
}
pub fn test() {
let mut args: Vec<Test> = vec![];
// Forward
args.sort_by(|a, b| a.name().cmp(b.name()));
args.sort_by(|a, b| a.wrapped().cmp(&b.wrapped()));
args.sort_unstable_by(|a, b| a.name().cmp(b.name()));
args.sort_unstable_by(|a, b| a.wrapped().cmp(&b.wrapped()));
// Reverse
args.sort_by(|a, b| b.name().cmp(a.name()));
args.sort_by(|a, b| b.wrapped().cmp(&a.wrapped()));
args.sort_unstable_by(|a, b| b.name().cmp(a.name()));
args.sort_unstable_by(|a, b| b.wrapped().cmp(&a.wrapped()));
}
}
// The closure parameter is not dereferenced anymore, so non-Copy types can be linted
mod issue_6001 {
use super::*;
struct Test(String);
impl Test {
// Return an owned type so that we don't hit the fix for 5754
fn name(&self) -> String {
self.0.clone()
}
}
pub fn
|
() {
let mut args: Vec<Test> = vec![];
// Forward
args.sort_by(|a, b| a.name().cmp(&b.name()));
args.sort_unstable_by(|a, b| a.name().cmp(&b.name()));
// Reverse
args.sort_by(|a, b| b.name().cmp(&a.name()));
args.sort_unstable_by(|a, b| b.name().cmp(&a.name()));
}
}
fn main() {
unnecessary_sort_by();
issue_5754::test();
issue_6001::test();
}
|
test
|
identifier_name
|
xfstate.rs
|
extern crate gears;
use gears::structure::xflow::*;
use gears::runtime::xfstate::*;
#[cfg(test)]
#[test]
fn test_store_has() {
let mut xfstate = XFState::default();
let xvar = XFlowVariable {
name: "number1".to_string(),
vtype: XFlowValueType::String,
value: XFlowValue::String("number1".to_owned()),
};
assert_eq!(xfstate.len(), 0);
assert_eq!(xfstate.is_empty(), true);
xfstate.add(&xvar);
|
assert_eq!(xfstate.has("number1"), true);
match xfstate.get("number1") {
Some(res) => assert_eq!(res.name, "number1"),
None => println!("Error, number1 not found in xfstate"),
}
}
#[test]
fn test_store_add_and_remove() {
let mut xfstate = XFState::default();
let xvar = XFlowVariable {
name: "number1".to_string(),
vtype: XFlowValueType::String,
value: XFlowValue::String("number1".to_owned()),
};
xfstate.add(&xvar);
assert_eq!(xfstate.has("number1"), true);
xfstate.remove("number1");
assert_eq!(xfstate.has("number1"), false);
assert_eq!(xfstate.is_empty(), true);
}
|
assert_eq!(xfstate.len(), 1);
assert_eq!(xfstate.is_empty(), false);
|
random_line_split
|
xfstate.rs
|
extern crate gears;
use gears::structure::xflow::*;
use gears::runtime::xfstate::*;
#[cfg(test)]
#[test]
fn test_store_has() {
let mut xfstate = XFState::default();
let xvar = XFlowVariable {
name: "number1".to_string(),
vtype: XFlowValueType::String,
value: XFlowValue::String("number1".to_owned()),
};
assert_eq!(xfstate.len(), 0);
assert_eq!(xfstate.is_empty(), true);
xfstate.add(&xvar);
assert_eq!(xfstate.len(), 1);
assert_eq!(xfstate.is_empty(), false);
assert_eq!(xfstate.has("number1"), true);
match xfstate.get("number1") {
Some(res) => assert_eq!(res.name, "number1"),
None => println!("Error, number1 not found in xfstate"),
}
}
#[test]
fn test_store_add_and_remove()
|
{
let mut xfstate = XFState::default();
let xvar = XFlowVariable {
name: "number1".to_string(),
vtype: XFlowValueType::String,
value: XFlowValue::String("number1".to_owned()),
};
xfstate.add(&xvar);
assert_eq!(xfstate.has("number1"), true);
xfstate.remove("number1");
assert_eq!(xfstate.has("number1"), false);
assert_eq!(xfstate.is_empty(), true);
}
|
identifier_body
|
|
xfstate.rs
|
extern crate gears;
use gears::structure::xflow::*;
use gears::runtime::xfstate::*;
#[cfg(test)]
#[test]
fn
|
() {
let mut xfstate = XFState::default();
let xvar = XFlowVariable {
name: "number1".to_string(),
vtype: XFlowValueType::String,
value: XFlowValue::String("number1".to_owned()),
};
assert_eq!(xfstate.len(), 0);
assert_eq!(xfstate.is_empty(), true);
xfstate.add(&xvar);
assert_eq!(xfstate.len(), 1);
assert_eq!(xfstate.is_empty(), false);
assert_eq!(xfstate.has("number1"), true);
match xfstate.get("number1") {
Some(res) => assert_eq!(res.name, "number1"),
None => println!("Error, number1 not found in xfstate"),
}
}
#[test]
fn test_store_add_and_remove() {
let mut xfstate = XFState::default();
let xvar = XFlowVariable {
name: "number1".to_string(),
vtype: XFlowValueType::String,
value: XFlowValue::String("number1".to_owned()),
};
xfstate.add(&xvar);
assert_eq!(xfstate.has("number1"), true);
xfstate.remove("number1");
assert_eq!(xfstate.has("number1"), false);
assert_eq!(xfstate.is_empty(), true);
}
|
test_store_has
|
identifier_name
|
kunpckdq.rs
|
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
fn
|
() {
run_test(&Instruction { mnemonic: Mnemonic::KUNPCKDQ, operand1: Some(Direct(K5)), operand2: Some(Direct(K2)), operand3: Some(Direct(K6)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[196, 225, 236, 75, 238], OperandSize::Dword)
}
fn kunpckdq_2() {
run_test(&Instruction { mnemonic: Mnemonic::KUNPCKDQ, operand1: Some(Direct(K7)), operand2: Some(Direct(K1)), operand3: Some(Direct(K4)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[196, 225, 244, 75, 252], OperandSize::Qword)
}
|
kunpckdq_1
|
identifier_name
|
kunpckdq.rs
|
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
fn kunpckdq_1() {
run_test(&Instruction { mnemonic: Mnemonic::KUNPCKDQ, operand1: Some(Direct(K5)), operand2: Some(Direct(K2)), operand3: Some(Direct(K6)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[196, 225, 236, 75, 238], OperandSize::Dword)
}
fn kunpckdq_2()
|
{
run_test(&Instruction { mnemonic: Mnemonic::KUNPCKDQ, operand1: Some(Direct(K7)), operand2: Some(Direct(K1)), operand3: Some(Direct(K4)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[196, 225, 244, 75, 252], OperandSize::Qword)
}
|
identifier_body
|
|
kunpckdq.rs
|
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
|
fn kunpckdq_1() {
run_test(&Instruction { mnemonic: Mnemonic::KUNPCKDQ, operand1: Some(Direct(K5)), operand2: Some(Direct(K2)), operand3: Some(Direct(K6)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[196, 225, 236, 75, 238], OperandSize::Dword)
}
fn kunpckdq_2() {
run_test(&Instruction { mnemonic: Mnemonic::KUNPCKDQ, operand1: Some(Direct(K7)), operand2: Some(Direct(K1)), operand3: Some(Direct(K4)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[196, 225, 244, 75, 252], OperandSize::Qword)
}
|
random_line_split
|
|
main.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 that removing an upstream crate does not cause any trouble.
// revisions:rpass1 rpass2
// aux-build:extern_crate.rs
#[cfg(rpass1)]
extern crate extern_crate;
pub fn main() {
#[cfg(rpass1)]
{
extern_crate::foo(1);
}
#[cfg(rpass2)]
{
foo(1);
|
#[cfg(rpass2)]
pub fn foo(_: u8) {
}
|
}
}
|
random_line_split
|
main.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 that removing an upstream crate does not cause any trouble.
// revisions:rpass1 rpass2
// aux-build:extern_crate.rs
#[cfg(rpass1)]
extern crate extern_crate;
pub fn main()
|
#[cfg(rpass2)]
pub fn foo(_: u8) {
}
|
{
#[cfg(rpass1)]
{
extern_crate::foo(1);
}
#[cfg(rpass2)]
{
foo(1);
}
}
|
identifier_body
|
main.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 that removing an upstream crate does not cause any trouble.
// revisions:rpass1 rpass2
// aux-build:extern_crate.rs
#[cfg(rpass1)]
extern crate extern_crate;
pub fn main() {
#[cfg(rpass1)]
{
extern_crate::foo(1);
}
#[cfg(rpass2)]
{
foo(1);
}
}
#[cfg(rpass2)]
pub fn
|
(_: u8) {
}
|
foo
|
identifier_name
|
third.rs
|
use std::rc::Rc;
pub struct List<T> {
head: Link<T>,
}
type Link<T> = Option<Rc<Node<T>>>;
struct Node<T> {
elem: T,
next: Link<T>,
}
pub struct Iter<'a, T:'a> {
next: Option<&'a Node<T>>,
}
impl<T> List<T> {
pub fn new() -> Self
|
pub fn append(&self, elem: T) -> List<T> {
List { head: Some(Rc::new(Node {
elem: elem,
next: self.head.clone(),
}))}
}
pub fn tail(&self) -> List<T> {
List { head: self.head.as_ref().and_then(|node| node.next.clone()) }
}
pub fn head(&self) -> Option<&T> {
self.head.as_ref().map(|node| &node.elem)
}
pub fn iter(&self) -> Iter<T> {
Iter { next: self.head.as_ref().map(|node| &**node) }
}
}
impl<'a, T> Iterator for Iter<'a, T> {
type Item = &'a T;
fn next(&mut self) -> Option<Self::Item> {
self.next.map(|node| {
self.next = node.next.as_ref().map(|node| &**node);
&node.elem
})
}
}
#[cfg(test)]
mod test {
use super::List;
#[test]
fn basics() {
let list = List::new();
assert_eq!(list.head(), None);
let list = list.append(1).append(2).append(3);
assert_eq!(list.head(), Some(&3));
let list = list.tail();
assert_eq!(list.head(), Some(&2));
let list = list.tail();
assert_eq!(list.head(), Some(&1));
let list = list.tail();
assert_eq!(list.head(), None);
// Make sure empty tail works
let list = list.tail();
assert_eq!(list.head(), None);
}
#[test]
fn iter() {
let list = List::new().append(1).append(2).append(3);
let mut iter = list.iter();
assert_eq!(iter.next(), Some(&3));
assert_eq!(iter.next(), Some(&2));
assert_eq!(iter.next(), Some(&1));
}
}
|
{
List { head: None }
}
|
identifier_body
|
third.rs
|
use std::rc::Rc;
pub struct List<T> {
head: Link<T>,
}
type Link<T> = Option<Rc<Node<T>>>;
struct Node<T> {
elem: T,
next: Link<T>,
}
pub struct Iter<'a, T:'a> {
next: Option<&'a Node<T>>,
}
impl<T> List<T> {
pub fn new() -> Self {
List { head: None }
}
pub fn append(&self, elem: T) -> List<T> {
List { head: Some(Rc::new(Node {
elem: elem,
next: self.head.clone(),
}))}
}
pub fn
|
(&self) -> List<T> {
List { head: self.head.as_ref().and_then(|node| node.next.clone()) }
}
pub fn head(&self) -> Option<&T> {
self.head.as_ref().map(|node| &node.elem)
}
pub fn iter(&self) -> Iter<T> {
Iter { next: self.head.as_ref().map(|node| &**node) }
}
}
impl<'a, T> Iterator for Iter<'a, T> {
type Item = &'a T;
fn next(&mut self) -> Option<Self::Item> {
self.next.map(|node| {
self.next = node.next.as_ref().map(|node| &**node);
&node.elem
})
}
}
#[cfg(test)]
mod test {
use super::List;
#[test]
fn basics() {
let list = List::new();
assert_eq!(list.head(), None);
let list = list.append(1).append(2).append(3);
assert_eq!(list.head(), Some(&3));
let list = list.tail();
assert_eq!(list.head(), Some(&2));
let list = list.tail();
assert_eq!(list.head(), Some(&1));
let list = list.tail();
assert_eq!(list.head(), None);
// Make sure empty tail works
let list = list.tail();
assert_eq!(list.head(), None);
}
#[test]
fn iter() {
let list = List::new().append(1).append(2).append(3);
let mut iter = list.iter();
assert_eq!(iter.next(), Some(&3));
assert_eq!(iter.next(), Some(&2));
assert_eq!(iter.next(), Some(&1));
}
}
|
tail
|
identifier_name
|
third.rs
|
use std::rc::Rc;
pub struct List<T> {
head: Link<T>,
}
type Link<T> = Option<Rc<Node<T>>>;
struct Node<T> {
elem: T,
next: Link<T>,
}
pub struct Iter<'a, T:'a> {
next: Option<&'a Node<T>>,
}
impl<T> List<T> {
pub fn new() -> Self {
List { head: None }
}
pub fn append(&self, elem: T) -> List<T> {
List { head: Some(Rc::new(Node {
elem: elem,
next: self.head.clone(),
}))}
}
pub fn tail(&self) -> List<T> {
List { head: self.head.as_ref().and_then(|node| node.next.clone()) }
}
pub fn head(&self) -> Option<&T> {
self.head.as_ref().map(|node| &node.elem)
}
pub fn iter(&self) -> Iter<T> {
Iter { next: self.head.as_ref().map(|node| &**node) }
}
}
impl<'a, T> Iterator for Iter<'a, T> {
type Item = &'a T;
fn next(&mut self) -> Option<Self::Item> {
self.next.map(|node| {
self.next = node.next.as_ref().map(|node| &**node);
&node.elem
})
}
}
#[cfg(test)]
mod test {
use super::List;
#[test]
fn basics() {
let list = List::new();
assert_eq!(list.head(), None);
let list = list.append(1).append(2).append(3);
assert_eq!(list.head(), Some(&3));
let list = list.tail();
assert_eq!(list.head(), Some(&2));
let list = list.tail();
assert_eq!(list.head(), Some(&1));
let list = list.tail();
assert_eq!(list.head(), None);
// Make sure empty tail works
let list = list.tail();
assert_eq!(list.head(), None);
|
#[test]
fn iter() {
let list = List::new().append(1).append(2).append(3);
let mut iter = list.iter();
assert_eq!(iter.next(), Some(&3));
assert_eq!(iter.next(), Some(&2));
assert_eq!(iter.next(), Some(&1));
}
}
|
}
|
random_line_split
|
htmltableheadercellelement.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::HTMLTableHeaderCellElementBinding;
use dom::bindings::codegen::InheritTypes::HTMLTableHeaderCellElementDerived;
use dom::bindings::js::{JSRef, Temporary};
use dom::bindings::utils::{Reflectable, Reflector};
use dom::document::Document;
use dom::element::HTMLTableHeaderCellElementTypeId;
use dom::eventtarget::{EventTarget, NodeTargetTypeId};
use dom::htmltablecellelement::HTMLTableCellElement;
use dom::node::{Node, ElementNodeTypeId};
use servo_util::str::DOMString;
#[deriving(Encodable)]
#[must_root]
pub struct HTMLTableHeaderCellElement {
pub htmltablecellelement: HTMLTableCellElement,
}
|
impl HTMLTableHeaderCellElement {
pub fn new_inherited(localName: DOMString, document: JSRef<Document>) -> HTMLTableHeaderCellElement {
HTMLTableHeaderCellElement {
htmltablecellelement: HTMLTableCellElement::new_inherited(HTMLTableHeaderCellElementTypeId, localName, document)
}
}
#[allow(unrooted_must_root)]
pub fn new(localName: DOMString, document: JSRef<Document>) -> Temporary<HTMLTableHeaderCellElement> {
let element = HTMLTableHeaderCellElement::new_inherited(localName, document);
Node::reflect_node(box element, document, HTMLTableHeaderCellElementBinding::Wrap)
}
}
impl Reflectable for HTMLTableHeaderCellElement {
fn reflector<'a>(&'a self) -> &'a Reflector {
self.htmltablecellelement.reflector()
}
}
|
impl HTMLTableHeaderCellElementDerived for EventTarget {
fn is_htmltableheadercellelement(&self) -> bool {
self.type_id == NodeTargetTypeId(ElementNodeTypeId(HTMLTableHeaderCellElementTypeId))
}
}
|
random_line_split
|
htmltableheadercellelement.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::HTMLTableHeaderCellElementBinding;
use dom::bindings::codegen::InheritTypes::HTMLTableHeaderCellElementDerived;
use dom::bindings::js::{JSRef, Temporary};
use dom::bindings::utils::{Reflectable, Reflector};
use dom::document::Document;
use dom::element::HTMLTableHeaderCellElementTypeId;
use dom::eventtarget::{EventTarget, NodeTargetTypeId};
use dom::htmltablecellelement::HTMLTableCellElement;
use dom::node::{Node, ElementNodeTypeId};
use servo_util::str::DOMString;
#[deriving(Encodable)]
#[must_root]
pub struct HTMLTableHeaderCellElement {
pub htmltablecellelement: HTMLTableCellElement,
}
impl HTMLTableHeaderCellElementDerived for EventTarget {
fn is_htmltableheadercellelement(&self) -> bool {
self.type_id == NodeTargetTypeId(ElementNodeTypeId(HTMLTableHeaderCellElementTypeId))
}
}
impl HTMLTableHeaderCellElement {
pub fn new_inherited(localName: DOMString, document: JSRef<Document>) -> HTMLTableHeaderCellElement
|
#[allow(unrooted_must_root)]
pub fn new(localName: DOMString, document: JSRef<Document>) -> Temporary<HTMLTableHeaderCellElement> {
let element = HTMLTableHeaderCellElement::new_inherited(localName, document);
Node::reflect_node(box element, document, HTMLTableHeaderCellElementBinding::Wrap)
}
}
impl Reflectable for HTMLTableHeaderCellElement {
fn reflector<'a>(&'a self) -> &'a Reflector {
self.htmltablecellelement.reflector()
}
}
|
{
HTMLTableHeaderCellElement {
htmltablecellelement: HTMLTableCellElement::new_inherited(HTMLTableHeaderCellElementTypeId, localName, document)
}
}
|
identifier_body
|
htmltableheadercellelement.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::HTMLTableHeaderCellElementBinding;
use dom::bindings::codegen::InheritTypes::HTMLTableHeaderCellElementDerived;
use dom::bindings::js::{JSRef, Temporary};
use dom::bindings::utils::{Reflectable, Reflector};
use dom::document::Document;
use dom::element::HTMLTableHeaderCellElementTypeId;
use dom::eventtarget::{EventTarget, NodeTargetTypeId};
use dom::htmltablecellelement::HTMLTableCellElement;
use dom::node::{Node, ElementNodeTypeId};
use servo_util::str::DOMString;
#[deriving(Encodable)]
#[must_root]
pub struct HTMLTableHeaderCellElement {
pub htmltablecellelement: HTMLTableCellElement,
}
impl HTMLTableHeaderCellElementDerived for EventTarget {
fn is_htmltableheadercellelement(&self) -> bool {
self.type_id == NodeTargetTypeId(ElementNodeTypeId(HTMLTableHeaderCellElementTypeId))
}
}
impl HTMLTableHeaderCellElement {
pub fn
|
(localName: DOMString, document: JSRef<Document>) -> HTMLTableHeaderCellElement {
HTMLTableHeaderCellElement {
htmltablecellelement: HTMLTableCellElement::new_inherited(HTMLTableHeaderCellElementTypeId, localName, document)
}
}
#[allow(unrooted_must_root)]
pub fn new(localName: DOMString, document: JSRef<Document>) -> Temporary<HTMLTableHeaderCellElement> {
let element = HTMLTableHeaderCellElement::new_inherited(localName, document);
Node::reflect_node(box element, document, HTMLTableHeaderCellElementBinding::Wrap)
}
}
impl Reflectable for HTMLTableHeaderCellElement {
fn reflector<'a>(&'a self) -> &'a Reflector {
self.htmltablecellelement.reflector()
}
}
|
new_inherited
|
identifier_name
|
thread.rs
|
// "Tifflin" Kernel
// - By John Hodge (thePowersGang)
|
//
// Core/threads/thread.rs
//! Representation of an active thread
/**
* Ownership
* =========
*
* The `Thread` struct is owned by the thread itself (the pointer stored within TLS)
* however, it points to a shared block that contains information needed by both the
* thread itself, and the "owner" of the thread (e.g process, or controlling driver).
*/
use prelude::*;
use lib::mem::Arc;
/// Thread identifier (unique)
pub type ThreadID = u32;
pub type ProcessID = u32;
//#[deriving(PartialEq)]
/// Thread run state
pub enum RunState
{
/// Runnable = Can be executed (either currently running, or on the active queue)
Runnable,
/// Sleeping on a WaitQueue
ListWait(*const super::WaitQueue),
/// Sleeping on a SleepObject
Sleep(*const super::sleep_object::SleepObject),
/// Dead, waiting to be reaped
Dead(u32),
}
// Sendable, the objects it points to must be either boxed or'static
unsafe impl Send for RunState { }
impl Default for RunState { fn default() -> RunState { RunState::Runnable } }
pub struct Process
{
name: String,
pid: ProcessID,
address_space: ::memory::virt::AddressSpace,
// TODO: use of a tuple here looks a little crufty
exit_status: ::sync::Mutex< (Option<u32>, Option<::threads::sleep_object::SleepObjectRef>) >,
pub proc_local_data: ::sync::RwLock<Vec< ::lib::mem::aref::Aref<::core::any::Any+Sync+Send> >>,
}
/// Handle to a process, used for spawning and communicating
pub struct ProcessHandle(Arc<Process>);
impl_fmt! {
Debug(self, f) for ProcessHandle {
write!(f, "P({} {})", self.0.pid, self.0.name)
}
}
struct SharedBlock
{
name: String,
tid: ThreadID,
process: Arc<Process>,
}
/// An owning thread handle
pub struct ThreadHandle
{
block: Arc<SharedBlock>,
// TODO: Also store a pointer to the 'Thread' struct?
// - Race problems
}
/// Thread information
pub struct Thread
{
block: Arc<SharedBlock>,
/// Execution state
pub run_state: RunState,
/// CPU state
pub cpu_state: ::arch::threads::State,
/// Next thread in intrusive list
pub next: Option<Box<Thread>>,
}
assert_trait!{Thread : Send}
/// Last allocated TID (because TID0 is allocated differently)
static S_LAST_TID: ::core::sync::atomic::AtomicUsize = ::core::sync::atomic::ATOMIC_USIZE_INIT;
const C_MAX_TID: usize = 0x7FFF_FFF0; // Leave 16 TIDs spare at end of 31 bit number
static S_LAST_PID: ::core::sync::atomic::AtomicUsize = ::core::sync::atomic::ATOMIC_USIZE_INIT;
const C_MAX_PID: usize = 0x007F_FFF0; // Leave 16 PIDs spare at end of 23 bit number
fn allocate_tid() -> ThreadID
{
// Preemptively prevent rollover
if S_LAST_TID.load(::core::sync::atomic::Ordering::Relaxed) == C_MAX_TID - 1 {
panic!("TODO: Handle TID exhaustion by searching for free");
}
let rv = S_LAST_TID.fetch_add(1, ::core::sync::atomic::Ordering::Relaxed);
// Handle rollover after (in case of heavy contention)
if rv >= C_MAX_TID {
panic!("TODO: Handle TID exhaustion by searching for free (raced)");
}
(rv + 1) as ThreadID
}
fn allocate_pid() -> u32
{
// Preemptively prevent rollover
if S_LAST_PID.load(::core::sync::atomic::Ordering::Relaxed) == C_MAX_PID - 1 {
panic!("TODO: Handle PID exhaustion by searching for free");
}
let rv = S_LAST_PID.fetch_add(1, ::core::sync::atomic::Ordering::Relaxed);
// Handle rollover after (in case of heavy contention)
if rv >= C_MAX_PID {
panic!("TODO: Handle PID exhaustion by searching for free (raced)");
}
(rv + 1) as u32
}
impl Process
{
pub fn new_pid0() -> Arc<Process> {
Arc::new(Process {
name: String::from("PID0"),
pid: 0,
exit_status: Default::default(),
address_space: ::memory::virt::AddressSpace::pid0(),
proc_local_data: ::sync::RwLock::new( Vec::new() ),
})
}
pub fn new<S: Into<String>+::core::fmt::Debug>(name: S, addr_space: ::memory::virt::AddressSpace) -> Arc<Process>
{
Arc::new(Process {
pid: allocate_pid(),
name: name.into(),
exit_status: Default::default(),
address_space: addr_space,
proc_local_data: ::sync::RwLock::new( Vec::new() ),
})
}
fn empty_cpu_state(&self) -> ::arch::threads::State {
::arch::threads::State::new( &self.address_space )
}
pub fn get_pid(&self) -> ProcessID { self.pid }
pub fn mark_exit(&self, status: u32) -> Result<(),()> {
let mut lh = self.exit_status.lock();
if lh.0.is_some() {
Err( () )
}
else {
if let Some(ref sleep_ref) = lh.1 {
sleep_ref.signal();
}
lh.0 = Some(status);
Ok( () )
}
}
}
impl ProcessHandle
{
pub fn new<S: Into<String>+::core::fmt::Debug>(name: S, clone_start: usize, clone_end: usize) -> ProcessHandle {
ProcessHandle( Process::new(name, ::memory::virt::AddressSpace::new(clone_start, clone_end)) )
}
pub fn start_root_thread(&mut self, ip: usize, sp: usize) {
assert!( ::lib::mem::arc::get_mut(&mut self.0).is_some() );
let mut thread = Thread::new_boxed(allocate_tid(), format!("{}#1", self.0.name), self.0.clone());
::arch::threads::start_thread( &mut thread,
// SAFE: Well... trusting caller to give us sane addresses etc, but that's the user's problem
move || unsafe {
log_debug!("Dropping to {:#x} SP={:#x}", ip, sp);
::arch::drop_to_user(ip, sp, 0)
}
);
super::yield_to(thread);
}
pub fn get_process_local<T: Send+Sync+::core::marker::Reflect+Default+'static>(&self) -> Option<::lib::mem::aref::ArefBorrow<T>> {
let pld = &self.0.proc_local_data;
// 1. Try without write-locking
for s in pld.read().iter()
{
let item_ref: &::core::any::Any = &**s;
if item_ref.get_type_id() == ::core::any::TypeId::of::<T>() {
return Some( s.borrow().downcast::<T>().ok().unwrap() );
}
}
None
}
pub fn bind_wait_terminate(&self, obj: &mut ::threads::SleepObject) {
let mut lh = self.0.exit_status.lock();
if let Some(_status) = lh.0 {
obj.signal();
}
else if let Some(_) = lh.1 {
todo!("Multiple threads sleeping on this process");
}
else {
lh.1 = Some( obj.get_ref() );
}
}
pub fn clear_wait_terminate(&self, obj: &mut ::threads::SleepObject) -> bool {
let mut lh = self.0.exit_status.lock();
assert!(lh.1.is_some());
assert!(lh.1.as_ref().unwrap().is_from(obj));
lh.1 = None;
lh.0.is_some()
}
pub fn get_exit_status(&self) -> Option<u32> {
self.0.exit_status.lock().0
}
}
impl ThreadHandle
{
pub fn new<F: FnOnce()+Send+'static, S: Into<String>>(name: S, fcn: F, process: Arc<Process>) -> ThreadHandle
{
let mut thread = Thread::new_boxed(allocate_tid(), name, process);
let handle = ThreadHandle {
block: thread.block.clone(),
};
::arch::threads::start_thread(&mut thread, fcn);
// Yield to this thread
super::yield_to(thread);
handle
}
}
impl ::core::fmt::Debug for ThreadHandle
{
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> Result<(),::core::fmt::Error>
{
write!(f, "ThreadHandle({})", self.block)
}
}
impl ::core::ops::Drop for ThreadHandle
{
fn drop(&mut self) {
panic!("TODO: Wait for thread to terminate when handle is dropped");
}
}
impl Thread
{
/// Create a new thread
pub fn new_boxed<S: Into<String>>(tid: ThreadID, name: S, process: Arc<Process>) -> Box<Thread>
{
let rv = box Thread {
cpu_state: process.empty_cpu_state(),
block: Arc::new( SharedBlock { tid: tid, name: name.into(), process: process } ),
run_state: RunState::Runnable,
next: None,
};
// TODO: Add to global list of threads (removed on destroy)
log_debug!("Creating thread {:?}", rv);
rv
}
pub fn get_tid(&self) -> ThreadID { self.block.tid }
/// Set the execution state of this thread
pub fn set_state(&mut self, state: RunState) {
self.run_state = state;
}
pub fn is_runnable(&self) -> bool { is!(self.run_state, RunState::Runnable) }
/// Assert that this thread is runnable
pub fn assert_active(&self) {
assert!(!is!(self.run_state, RunState::Sleep(_)) );
assert!(!is!(self.run_state, RunState::ListWait(_)) );
assert!( is!(self.run_state, RunState::Runnable) );
}
pub fn get_process_info(&self) -> &Process {
&*self.block.process
}
}
impl ::core::fmt::Display for SharedBlock
{
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result
{
write!(f, "{} {}", self.tid, self.name)
}
}
impl ::core::fmt::Debug for Thread
{
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> Result<(),::core::fmt::Error>
{
write!(f, "{:p}({})", self, self.block)
}
}
impl_fmt! {
Display(self, f) for Process {
write!(f, "PID{}:'{}'", self.pid, self.name)
}
}
impl ::core::ops::Drop for Thread
{
fn drop(&mut self)
{
// TODO: Remove self from the global thread map
log_debug!("Destroying thread {:?}", self);
}
}
|
random_line_split
|
|
thread.rs
|
// "Tifflin" Kernel
// - By John Hodge (thePowersGang)
//
// Core/threads/thread.rs
//! Representation of an active thread
/**
* Ownership
* =========
*
* The `Thread` struct is owned by the thread itself (the pointer stored within TLS)
* however, it points to a shared block that contains information needed by both the
* thread itself, and the "owner" of the thread (e.g process, or controlling driver).
*/
use prelude::*;
use lib::mem::Arc;
/// Thread identifier (unique)
pub type ThreadID = u32;
pub type ProcessID = u32;
//#[deriving(PartialEq)]
/// Thread run state
pub enum RunState
{
/// Runnable = Can be executed (either currently running, or on the active queue)
Runnable,
/// Sleeping on a WaitQueue
ListWait(*const super::WaitQueue),
/// Sleeping on a SleepObject
Sleep(*const super::sleep_object::SleepObject),
/// Dead, waiting to be reaped
Dead(u32),
}
// Sendable, the objects it points to must be either boxed or'static
unsafe impl Send for RunState { }
impl Default for RunState { fn default() -> RunState { RunState::Runnable } }
pub struct Process
{
name: String,
pid: ProcessID,
address_space: ::memory::virt::AddressSpace,
// TODO: use of a tuple here looks a little crufty
exit_status: ::sync::Mutex< (Option<u32>, Option<::threads::sleep_object::SleepObjectRef>) >,
pub proc_local_data: ::sync::RwLock<Vec< ::lib::mem::aref::Aref<::core::any::Any+Sync+Send> >>,
}
/// Handle to a process, used for spawning and communicating
pub struct ProcessHandle(Arc<Process>);
impl_fmt! {
Debug(self, f) for ProcessHandle {
write!(f, "P({} {})", self.0.pid, self.0.name)
}
}
struct SharedBlock
{
name: String,
tid: ThreadID,
process: Arc<Process>,
}
/// An owning thread handle
pub struct ThreadHandle
{
block: Arc<SharedBlock>,
// TODO: Also store a pointer to the 'Thread' struct?
// - Race problems
}
/// Thread information
pub struct Thread
{
block: Arc<SharedBlock>,
/// Execution state
pub run_state: RunState,
/// CPU state
pub cpu_state: ::arch::threads::State,
/// Next thread in intrusive list
pub next: Option<Box<Thread>>,
}
assert_trait!{Thread : Send}
/// Last allocated TID (because TID0 is allocated differently)
static S_LAST_TID: ::core::sync::atomic::AtomicUsize = ::core::sync::atomic::ATOMIC_USIZE_INIT;
const C_MAX_TID: usize = 0x7FFF_FFF0; // Leave 16 TIDs spare at end of 31 bit number
static S_LAST_PID: ::core::sync::atomic::AtomicUsize = ::core::sync::atomic::ATOMIC_USIZE_INIT;
const C_MAX_PID: usize = 0x007F_FFF0; // Leave 16 PIDs spare at end of 23 bit number
fn allocate_tid() -> ThreadID
{
// Preemptively prevent rollover
if S_LAST_TID.load(::core::sync::atomic::Ordering::Relaxed) == C_MAX_TID - 1 {
panic!("TODO: Handle TID exhaustion by searching for free");
}
let rv = S_LAST_TID.fetch_add(1, ::core::sync::atomic::Ordering::Relaxed);
// Handle rollover after (in case of heavy contention)
if rv >= C_MAX_TID {
panic!("TODO: Handle TID exhaustion by searching for free (raced)");
}
(rv + 1) as ThreadID
}
fn allocate_pid() -> u32
{
// Preemptively prevent rollover
if S_LAST_PID.load(::core::sync::atomic::Ordering::Relaxed) == C_MAX_PID - 1 {
panic!("TODO: Handle PID exhaustion by searching for free");
}
let rv = S_LAST_PID.fetch_add(1, ::core::sync::atomic::Ordering::Relaxed);
// Handle rollover after (in case of heavy contention)
if rv >= C_MAX_PID {
panic!("TODO: Handle PID exhaustion by searching for free (raced)");
}
(rv + 1) as u32
}
impl Process
{
pub fn new_pid0() -> Arc<Process> {
Arc::new(Process {
name: String::from("PID0"),
pid: 0,
exit_status: Default::default(),
address_space: ::memory::virt::AddressSpace::pid0(),
proc_local_data: ::sync::RwLock::new( Vec::new() ),
})
}
pub fn new<S: Into<String>+::core::fmt::Debug>(name: S, addr_space: ::memory::virt::AddressSpace) -> Arc<Process>
{
Arc::new(Process {
pid: allocate_pid(),
name: name.into(),
exit_status: Default::default(),
address_space: addr_space,
proc_local_data: ::sync::RwLock::new( Vec::new() ),
})
}
fn empty_cpu_state(&self) -> ::arch::threads::State {
::arch::threads::State::new( &self.address_space )
}
pub fn get_pid(&self) -> ProcessID { self.pid }
pub fn mark_exit(&self, status: u32) -> Result<(),()> {
let mut lh = self.exit_status.lock();
if lh.0.is_some() {
Err( () )
}
else {
if let Some(ref sleep_ref) = lh.1
|
lh.0 = Some(status);
Ok( () )
}
}
}
impl ProcessHandle
{
pub fn new<S: Into<String>+::core::fmt::Debug>(name: S, clone_start: usize, clone_end: usize) -> ProcessHandle {
ProcessHandle( Process::new(name, ::memory::virt::AddressSpace::new(clone_start, clone_end)) )
}
pub fn start_root_thread(&mut self, ip: usize, sp: usize) {
assert!( ::lib::mem::arc::get_mut(&mut self.0).is_some() );
let mut thread = Thread::new_boxed(allocate_tid(), format!("{}#1", self.0.name), self.0.clone());
::arch::threads::start_thread( &mut thread,
// SAFE: Well... trusting caller to give us sane addresses etc, but that's the user's problem
move || unsafe {
log_debug!("Dropping to {:#x} SP={:#x}", ip, sp);
::arch::drop_to_user(ip, sp, 0)
}
);
super::yield_to(thread);
}
pub fn get_process_local<T: Send+Sync+::core::marker::Reflect+Default+'static>(&self) -> Option<::lib::mem::aref::ArefBorrow<T>> {
let pld = &self.0.proc_local_data;
// 1. Try without write-locking
for s in pld.read().iter()
{
let item_ref: &::core::any::Any = &**s;
if item_ref.get_type_id() == ::core::any::TypeId::of::<T>() {
return Some( s.borrow().downcast::<T>().ok().unwrap() );
}
}
None
}
pub fn bind_wait_terminate(&self, obj: &mut ::threads::SleepObject) {
let mut lh = self.0.exit_status.lock();
if let Some(_status) = lh.0 {
obj.signal();
}
else if let Some(_) = lh.1 {
todo!("Multiple threads sleeping on this process");
}
else {
lh.1 = Some( obj.get_ref() );
}
}
pub fn clear_wait_terminate(&self, obj: &mut ::threads::SleepObject) -> bool {
let mut lh = self.0.exit_status.lock();
assert!(lh.1.is_some());
assert!(lh.1.as_ref().unwrap().is_from(obj));
lh.1 = None;
lh.0.is_some()
}
pub fn get_exit_status(&self) -> Option<u32> {
self.0.exit_status.lock().0
}
}
impl ThreadHandle
{
pub fn new<F: FnOnce()+Send+'static, S: Into<String>>(name: S, fcn: F, process: Arc<Process>) -> ThreadHandle
{
let mut thread = Thread::new_boxed(allocate_tid(), name, process);
let handle = ThreadHandle {
block: thread.block.clone(),
};
::arch::threads::start_thread(&mut thread, fcn);
// Yield to this thread
super::yield_to(thread);
handle
}
}
impl ::core::fmt::Debug for ThreadHandle
{
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> Result<(),::core::fmt::Error>
{
write!(f, "ThreadHandle({})", self.block)
}
}
impl ::core::ops::Drop for ThreadHandle
{
fn drop(&mut self) {
panic!("TODO: Wait for thread to terminate when handle is dropped");
}
}
impl Thread
{
/// Create a new thread
pub fn new_boxed<S: Into<String>>(tid: ThreadID, name: S, process: Arc<Process>) -> Box<Thread>
{
let rv = box Thread {
cpu_state: process.empty_cpu_state(),
block: Arc::new( SharedBlock { tid: tid, name: name.into(), process: process } ),
run_state: RunState::Runnable,
next: None,
};
// TODO: Add to global list of threads (removed on destroy)
log_debug!("Creating thread {:?}", rv);
rv
}
pub fn get_tid(&self) -> ThreadID { self.block.tid }
/// Set the execution state of this thread
pub fn set_state(&mut self, state: RunState) {
self.run_state = state;
}
pub fn is_runnable(&self) -> bool { is!(self.run_state, RunState::Runnable) }
/// Assert that this thread is runnable
pub fn assert_active(&self) {
assert!(!is!(self.run_state, RunState::Sleep(_)) );
assert!(!is!(self.run_state, RunState::ListWait(_)) );
assert!( is!(self.run_state, RunState::Runnable) );
}
pub fn get_process_info(&self) -> &Process {
&*self.block.process
}
}
impl ::core::fmt::Display for SharedBlock
{
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result
{
write!(f, "{} {}", self.tid, self.name)
}
}
impl ::core::fmt::Debug for Thread
{
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> Result<(),::core::fmt::Error>
{
write!(f, "{:p}({})", self, self.block)
}
}
impl_fmt! {
Display(self, f) for Process {
write!(f, "PID{}:'{}'", self.pid, self.name)
}
}
impl ::core::ops::Drop for Thread
{
fn drop(&mut self)
{
// TODO: Remove self from the global thread map
log_debug!("Destroying thread {:?}", self);
}
}
|
{
sleep_ref.signal();
}
|
conditional_block
|
thread.rs
|
// "Tifflin" Kernel
// - By John Hodge (thePowersGang)
//
// Core/threads/thread.rs
//! Representation of an active thread
/**
* Ownership
* =========
*
* The `Thread` struct is owned by the thread itself (the pointer stored within TLS)
* however, it points to a shared block that contains information needed by both the
* thread itself, and the "owner" of the thread (e.g process, or controlling driver).
*/
use prelude::*;
use lib::mem::Arc;
/// Thread identifier (unique)
pub type ThreadID = u32;
pub type ProcessID = u32;
//#[deriving(PartialEq)]
/// Thread run state
pub enum RunState
{
/// Runnable = Can be executed (either currently running, or on the active queue)
Runnable,
/// Sleeping on a WaitQueue
ListWait(*const super::WaitQueue),
/// Sleeping on a SleepObject
Sleep(*const super::sleep_object::SleepObject),
/// Dead, waiting to be reaped
Dead(u32),
}
// Sendable, the objects it points to must be either boxed or'static
unsafe impl Send for RunState { }
impl Default for RunState { fn default() -> RunState { RunState::Runnable } }
pub struct Process
{
name: String,
pid: ProcessID,
address_space: ::memory::virt::AddressSpace,
// TODO: use of a tuple here looks a little crufty
exit_status: ::sync::Mutex< (Option<u32>, Option<::threads::sleep_object::SleepObjectRef>) >,
pub proc_local_data: ::sync::RwLock<Vec< ::lib::mem::aref::Aref<::core::any::Any+Sync+Send> >>,
}
/// Handle to a process, used for spawning and communicating
pub struct ProcessHandle(Arc<Process>);
impl_fmt! {
Debug(self, f) for ProcessHandle {
write!(f, "P({} {})", self.0.pid, self.0.name)
}
}
struct SharedBlock
{
name: String,
tid: ThreadID,
process: Arc<Process>,
}
/// An owning thread handle
pub struct ThreadHandle
{
block: Arc<SharedBlock>,
// TODO: Also store a pointer to the 'Thread' struct?
// - Race problems
}
/// Thread information
pub struct Thread
{
block: Arc<SharedBlock>,
/// Execution state
pub run_state: RunState,
/// CPU state
pub cpu_state: ::arch::threads::State,
/// Next thread in intrusive list
pub next: Option<Box<Thread>>,
}
assert_trait!{Thread : Send}
/// Last allocated TID (because TID0 is allocated differently)
static S_LAST_TID: ::core::sync::atomic::AtomicUsize = ::core::sync::atomic::ATOMIC_USIZE_INIT;
const C_MAX_TID: usize = 0x7FFF_FFF0; // Leave 16 TIDs spare at end of 31 bit number
static S_LAST_PID: ::core::sync::atomic::AtomicUsize = ::core::sync::atomic::ATOMIC_USIZE_INIT;
const C_MAX_PID: usize = 0x007F_FFF0; // Leave 16 PIDs spare at end of 23 bit number
fn allocate_tid() -> ThreadID
{
// Preemptively prevent rollover
if S_LAST_TID.load(::core::sync::atomic::Ordering::Relaxed) == C_MAX_TID - 1 {
panic!("TODO: Handle TID exhaustion by searching for free");
}
let rv = S_LAST_TID.fetch_add(1, ::core::sync::atomic::Ordering::Relaxed);
// Handle rollover after (in case of heavy contention)
if rv >= C_MAX_TID {
panic!("TODO: Handle TID exhaustion by searching for free (raced)");
}
(rv + 1) as ThreadID
}
fn allocate_pid() -> u32
{
// Preemptively prevent rollover
if S_LAST_PID.load(::core::sync::atomic::Ordering::Relaxed) == C_MAX_PID - 1 {
panic!("TODO: Handle PID exhaustion by searching for free");
}
let rv = S_LAST_PID.fetch_add(1, ::core::sync::atomic::Ordering::Relaxed);
// Handle rollover after (in case of heavy contention)
if rv >= C_MAX_PID {
panic!("TODO: Handle PID exhaustion by searching for free (raced)");
}
(rv + 1) as u32
}
impl Process
{
pub fn new_pid0() -> Arc<Process> {
Arc::new(Process {
name: String::from("PID0"),
pid: 0,
exit_status: Default::default(),
address_space: ::memory::virt::AddressSpace::pid0(),
proc_local_data: ::sync::RwLock::new( Vec::new() ),
})
}
pub fn new<S: Into<String>+::core::fmt::Debug>(name: S, addr_space: ::memory::virt::AddressSpace) -> Arc<Process>
{
Arc::new(Process {
pid: allocate_pid(),
name: name.into(),
exit_status: Default::default(),
address_space: addr_space,
proc_local_data: ::sync::RwLock::new( Vec::new() ),
})
}
fn empty_cpu_state(&self) -> ::arch::threads::State {
::arch::threads::State::new( &self.address_space )
}
pub fn get_pid(&self) -> ProcessID { self.pid }
pub fn mark_exit(&self, status: u32) -> Result<(),()> {
let mut lh = self.exit_status.lock();
if lh.0.is_some() {
Err( () )
}
else {
if let Some(ref sleep_ref) = lh.1 {
sleep_ref.signal();
}
lh.0 = Some(status);
Ok( () )
}
}
}
impl ProcessHandle
{
pub fn new<S: Into<String>+::core::fmt::Debug>(name: S, clone_start: usize, clone_end: usize) -> ProcessHandle {
ProcessHandle( Process::new(name, ::memory::virt::AddressSpace::new(clone_start, clone_end)) )
}
pub fn start_root_thread(&mut self, ip: usize, sp: usize) {
assert!( ::lib::mem::arc::get_mut(&mut self.0).is_some() );
let mut thread = Thread::new_boxed(allocate_tid(), format!("{}#1", self.0.name), self.0.clone());
::arch::threads::start_thread( &mut thread,
// SAFE: Well... trusting caller to give us sane addresses etc, but that's the user's problem
move || unsafe {
log_debug!("Dropping to {:#x} SP={:#x}", ip, sp);
::arch::drop_to_user(ip, sp, 0)
}
);
super::yield_to(thread);
}
pub fn
|
<T: Send+Sync+::core::marker::Reflect+Default+'static>(&self) -> Option<::lib::mem::aref::ArefBorrow<T>> {
let pld = &self.0.proc_local_data;
// 1. Try without write-locking
for s in pld.read().iter()
{
let item_ref: &::core::any::Any = &**s;
if item_ref.get_type_id() == ::core::any::TypeId::of::<T>() {
return Some( s.borrow().downcast::<T>().ok().unwrap() );
}
}
None
}
pub fn bind_wait_terminate(&self, obj: &mut ::threads::SleepObject) {
let mut lh = self.0.exit_status.lock();
if let Some(_status) = lh.0 {
obj.signal();
}
else if let Some(_) = lh.1 {
todo!("Multiple threads sleeping on this process");
}
else {
lh.1 = Some( obj.get_ref() );
}
}
pub fn clear_wait_terminate(&self, obj: &mut ::threads::SleepObject) -> bool {
let mut lh = self.0.exit_status.lock();
assert!(lh.1.is_some());
assert!(lh.1.as_ref().unwrap().is_from(obj));
lh.1 = None;
lh.0.is_some()
}
pub fn get_exit_status(&self) -> Option<u32> {
self.0.exit_status.lock().0
}
}
impl ThreadHandle
{
pub fn new<F: FnOnce()+Send+'static, S: Into<String>>(name: S, fcn: F, process: Arc<Process>) -> ThreadHandle
{
let mut thread = Thread::new_boxed(allocate_tid(), name, process);
let handle = ThreadHandle {
block: thread.block.clone(),
};
::arch::threads::start_thread(&mut thread, fcn);
// Yield to this thread
super::yield_to(thread);
handle
}
}
impl ::core::fmt::Debug for ThreadHandle
{
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> Result<(),::core::fmt::Error>
{
write!(f, "ThreadHandle({})", self.block)
}
}
impl ::core::ops::Drop for ThreadHandle
{
fn drop(&mut self) {
panic!("TODO: Wait for thread to terminate when handle is dropped");
}
}
impl Thread
{
/// Create a new thread
pub fn new_boxed<S: Into<String>>(tid: ThreadID, name: S, process: Arc<Process>) -> Box<Thread>
{
let rv = box Thread {
cpu_state: process.empty_cpu_state(),
block: Arc::new( SharedBlock { tid: tid, name: name.into(), process: process } ),
run_state: RunState::Runnable,
next: None,
};
// TODO: Add to global list of threads (removed on destroy)
log_debug!("Creating thread {:?}", rv);
rv
}
pub fn get_tid(&self) -> ThreadID { self.block.tid }
/// Set the execution state of this thread
pub fn set_state(&mut self, state: RunState) {
self.run_state = state;
}
pub fn is_runnable(&self) -> bool { is!(self.run_state, RunState::Runnable) }
/// Assert that this thread is runnable
pub fn assert_active(&self) {
assert!(!is!(self.run_state, RunState::Sleep(_)) );
assert!(!is!(self.run_state, RunState::ListWait(_)) );
assert!( is!(self.run_state, RunState::Runnable) );
}
pub fn get_process_info(&self) -> &Process {
&*self.block.process
}
}
impl ::core::fmt::Display for SharedBlock
{
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result
{
write!(f, "{} {}", self.tid, self.name)
}
}
impl ::core::fmt::Debug for Thread
{
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> Result<(),::core::fmt::Error>
{
write!(f, "{:p}({})", self, self.block)
}
}
impl_fmt! {
Display(self, f) for Process {
write!(f, "PID{}:'{}'", self.pid, self.name)
}
}
impl ::core::ops::Drop for Thread
{
fn drop(&mut self)
{
// TODO: Remove self from the global thread map
log_debug!("Destroying thread {:?}", self);
}
}
|
get_process_local
|
identifier_name
|
websocket_loader.rs
|
Name, Upgrade};
use hyper::http::h1::{LINE_ENDING, parse_response};
use hyper::method::Method;
use hyper::net::HttpStream;
use hyper::status::StatusCode;
use hyper::version::HttpVersion;
use ipc_channel::ipc::{IpcReceiver, IpcSender};
use net_traits::{CookieSource, MessageData, NetworkError};
use net_traits::{WebSocketDomAction, WebSocketNetworkEvent};
use net_traits::request::{Destination, RequestInit, RequestMode};
use servo_url::ServoUrl;
use std::io::{self, Write};
use std::net::TcpStream;
use std::sync::{Arc, Mutex};
use std::sync::atomic::{AtomicBool, Ordering};
use std::thread;
use url::Position;
use websocket::Message;
use websocket::header::{Origin, WebSocketAccept, WebSocketKey, WebSocketProtocol, WebSocketVersion};
use websocket::message::OwnedMessage;
use websocket::receiver::{Reader as WsReader, Receiver as WsReceiver};
use websocket::sender::{Sender as WsSender, Writer as WsWriter};
use websocket::ws::dataframe::DataFrame;
pub fn init(
req_init: RequestInit,
resource_event_sender: IpcSender<WebSocketNetworkEvent>,
dom_action_receiver: IpcReceiver<WebSocketDomAction>,
http_state: Arc<HttpState>
) {
thread::Builder::new().name(format!("WebSocket connection to {}", req_init.url)).spawn(move || {
let channel = establish_a_websocket_connection(req_init, &http_state);
let (ws_sender, mut receiver) = match channel {
Ok((protocol_in_use, sender, receiver)) =>
|
,
Err(e) => {
debug!("Failed to establish a WebSocket connection: {:?}", e);
let _ = resource_event_sender.send(WebSocketNetworkEvent::Fail);
return;
}
};
let initiated_close = Arc::new(AtomicBool::new(false));
let ws_sender = Arc::new(Mutex::new(ws_sender));
let initiated_close_incoming = initiated_close.clone();
let ws_sender_incoming = ws_sender.clone();
thread::spawn(move || {
for message in receiver.incoming_messages() {
let message = match message {
Ok(m) => m,
Err(e) => {
debug!("Error receiving incoming WebSocket message: {:?}", e);
let _ = resource_event_sender.send(WebSocketNetworkEvent::Fail);
break;
}
};
let message = match message {
OwnedMessage::Text(_) => {
MessageData::Text(String::from_utf8_lossy(&message.take_payload()).into_owned())
},
OwnedMessage::Binary(_) => MessageData::Binary(message.take_payload()),
OwnedMessage::Ping(_) => {
let pong = Message::pong(message.take_payload());
ws_sender_incoming.lock().unwrap().send_message(&pong).unwrap();
continue;
},
OwnedMessage::Pong(_) => continue,
OwnedMessage::Close(ref msg) => {
if!initiated_close_incoming.fetch_or(true, Ordering::SeqCst) {
ws_sender_incoming.lock().unwrap().send_message(&message).unwrap();
}
let (code, reason) = match *msg {
None => (None, "".into()),
Some(ref data) => (Some(data.status_code), data.reason.clone())
};
let _ = resource_event_sender.send(WebSocketNetworkEvent::Close(code, reason));
break;
},
};
let _ = resource_event_sender.send(WebSocketNetworkEvent::MessageReceived(message));
}
});
while let Ok(dom_action) = dom_action_receiver.recv() {
match dom_action {
WebSocketDomAction::SendMessage(MessageData::Text(data)) => {
ws_sender.lock().unwrap().send_message(&Message::text(data)).unwrap();
},
WebSocketDomAction::SendMessage(MessageData::Binary(data)) => {
ws_sender.lock().unwrap().send_message(&Message::binary(data)).unwrap();
},
WebSocketDomAction::Close(code, reason) => {
if!initiated_close.fetch_or(true, Ordering::SeqCst) {
let message = match code {
Some(code) => Message::close_because(code, reason.unwrap_or("".to_owned())),
None => Message::close()
};
ws_sender.lock().unwrap().send_message(&message).unwrap();
}
},
}
}
}).expect("Thread spawning failed");
}
type Stream = HttpStream;
// https://fetch.spec.whatwg.org/#concept-websocket-connection-obtain
fn obtain_a_websocket_connection(url: &ServoUrl) -> Result<Stream, NetworkError> {
// Step 1.
let host = url.host_str().unwrap();
// Step 2.
let port = url.port_or_known_default().unwrap();
// Step 3.
// We did not replace the scheme by "http" or "https" in step 1 of
// establish_a_websocket_connection.
let secure = match url.scheme() {
"ws" => false,
"wss" => true,
_ => panic!("URL's scheme should be ws or wss"),
};
if secure {
return Err(NetworkError::Internal("WSS is disabled for now.".into()));
}
// Steps 4-5.
let host = replace_host(host);
let tcp_stream = TcpStream::connect((&*host, port)).map_err(|e| {
NetworkError::Internal(format!("Could not connect to host: {}", e))
})?;
Ok(HttpStream(tcp_stream))
}
// https://fetch.spec.whatwg.org/#concept-websocket-establish
fn establish_a_websocket_connection(
req_init: RequestInit,
http_state: &HttpState
) -> Result<(Option<String>, WsWriter<HttpStream>, WsReader<HttpStream>), NetworkError>
{
let protocols = match req_init.mode {
RequestMode::WebSocket { protocols } => protocols.clone(),
_ => panic!("Received a RequestInit with a non-websocket mode in websocket_loader"),
};
// Steps 1 is not really applicable here, given we don't exactly go
// through the same infrastructure as the Fetch spec.
// Step 2, slimmed down because we don't go through the whole Fetch infra.
let mut headers = Headers::new();
// Step 3.
headers.set(Upgrade(vec![Protocol::new(ProtocolName::WebSocket, None)]));
// Step 4.
headers.set(Connection(vec![ConnectionOption::ConnectionHeader("upgrade".into())]));
// Step 5.
let key_value = WebSocketKey::new();
// Step 6.
headers.set(key_value);
// Step 7.
headers.set(WebSocketVersion::WebSocket13);
// Step 8.
if!protocols.is_empty() {
headers.set(WebSocketProtocol(protocols.clone()));
}
// Steps 9-10.
// TODO: handle permessage-deflate extension.
// Step 11 and network error check from step 12.
let response = fetch(req_init.url, req_init.origin.ascii_serialization(), headers, http_state)?;
// Step 12, the status code check.
if response.status!= StatusCode::SwitchingProtocols {
return Err(NetworkError::Internal("Response's status should be 101.".into()));
}
// Step 13.
if!protocols.is_empty() {
if response.headers.get::<WebSocketProtocol>().map_or(true, |protocols| protocols.is_empty()) {
return Err(NetworkError::Internal(
"Response's Sec-WebSocket-Protocol header is missing, malformed or empty.".into()));
}
}
// Step 14.2.
let upgrade_header = response.headers.get::<Upgrade>().ok_or_else(|| {
NetworkError::Internal("Response should have an Upgrade header.".into())
})?;
if upgrade_header.len()!= 1 {
return Err(NetworkError::Internal("Response's Upgrade header should have only one value.".into()));
}
if upgrade_header[0].name!= ProtocolName::WebSocket {
return Err(NetworkError::Internal("Response's Upgrade header value should be \"websocket\".".into()));
}
// Step 14.3.
let connection_header = response.headers.get::<Connection>().ok_or_else(|| {
NetworkError::Internal("Response should have a Connection header.".into())
})?;
let connection_includes_upgrade = connection_header.iter().any(|option| {
match *option {
ConnectionOption::ConnectionHeader(ref option) => *option == "upgrade",
_ => false,
}
});
if!connection_includes_upgrade {
return Err(NetworkError::Internal("Response's Connection header value should include \"upgrade\".".into()));
}
// Step 14.4.
let accept_header = response.headers.get::<WebSocketAccept>().ok_or_else(|| {
NetworkError::Internal("Response should have a Sec-Websocket-Accept header.".into())
})?;
if *accept_header!= WebSocketAccept::new(&key_value) {
return Err(NetworkError::Internal(
"Response's Sec-WebSocket-Accept header value did not match the sent key.".into()));
}
// Step 14.5.
// TODO: handle permessage-deflate extension.
// We don't support any extension, so we fail at the mere presence of
// a Sec-WebSocket-Extensions header.
if response.headers.get_raw("Sec-WebSocket-Extensions").is_some() {
return Err(NetworkError::Internal(
"Response's Sec-WebSocket-Extensions header value included unsupported extensions.".into()));
}
// Step 14.6.
let protocol_in_use = if let Some(response_protocols) = response.headers.get::<WebSocketProtocol>() {
for replied in &**response_protocols {
if!protocols.iter().any(|requested| requested.eq_ignore_ascii_case(replied)) {
return Err(NetworkError::Internal(
"Response's Sec-WebSocket-Protocols contain values that were not requested.".into()));
}
}
response_protocols.first().cloned()
} else {
None
};
let sender = WsSender::new(true);
let writer = WsWriter {
stream: response.writer,
sender
};
let receiver = WsReceiver::new(false);
let reader = WsReader {
stream: response.reader,
receiver,
};
Ok((protocol_in_use, writer, reader))
}
struct Response {
status: StatusCode,
headers: Headers,
reader: BufReader<Stream>,
writer: Stream,
}
// https://fetch.spec.whatwg.org/#concept-fetch
fn fetch(url: ServoUrl,
origin: String,
mut headers: Headers,
http_state: &HttpState)
-> Result<Response, NetworkError> {
// Step 1.
// TODO: handle request's window.
// Step 2.
// TODO: handle request's origin.
// Step 3.
set_default_accept(Destination::None, &mut headers);
// Step 4.
set_default_accept_language(&mut headers);
// Step 5.
// TODO: handle request's priority.
// Step 6.
// Not applicable: not a navigation request.
// Step 7.
// We know this is a subresource request.
{
// Step 7.1.
// Not applicable: client hints list is empty.
// Steps 7.2-3.
// TODO: handle fetch groups.
}
// Step 8.
main_fetch(url, origin, headers, http_state)
}
// https://fetch.spec.whatwg.org/#concept-main-fetch
fn main_fetch(url: ServoUrl,
origin: String,
mut headers: Headers,
http_state: &HttpState)
-> Result<Response, NetworkError> {
// Step 1.
let mut response = None;
// Step 2.
// Not applicable: request’s local-URLs-only flag is unset.
// Step 3.
// TODO: handle content security policy violations.
// Step 4.
// TODO: handle upgrade to a potentially secure URL.
// Step 5.
if should_be_blocked_due_to_bad_port(&url) {
response = Some(Err(NetworkError::Internal("Request should be blocked due to bad port.".into())));
}
// TODO: handle blocking as mixed content.
// TODO: handle blocking by content security policy.
// Steps 6-8.
// TODO: handle request's referrer policy.
// Step 9.
// Not applicable: request's current URL's scheme is not "ftp".
// Step 10.
// TODO: handle known HSTS host domain.
// Step 11.
// Not applicable: request's synchronous flag is set.
// Step 12.
let mut response = response.unwrap_or_else(|| {
// We must run the first sequence of substeps, given request's mode
// is "websocket".
// Step 12.1.
// Not applicable: the response is never exposed to the Web so it
// doesn't need to be filtered at all.
// Step 12.2.
scheme_fetch(&url, origin, &mut headers, http_state)
});
// Step 13.
// Not applicable: recursive flag is unset.
// Step 14.
// Not applicable: the response is never exposed to the Web so it doesn't
// need to be filtered at all.
// Steps 15-16.
// Not applicable: no need to maintain an internal response.
// Step 17.
if response.is_ok() {
// TODO: handle blocking as mixed content.
// TODO: handle blocking by content security policy.
// Not applicable: blocking due to MIME type matters only for scripts.
if should_be_blocked_due_to_nosniff(Destination::None, &headers) {
response = Err(NetworkError::Internal("Request should be blocked due to nosniff.".into()));
}
}
// Step 18.
// Not applicable: we don't care about the body at all.
// Step 19.
// Not applicable: request's integrity metadata is the empty string.
// Step 20.
// TODO: wait for response's body here, maybe?
response
}
// https://fetch.spec.whatwg.org/#concept-scheme-fetch
fn scheme_fetch(url: &ServoUrl,
origin: String,
headers: &mut Headers,
http_state: &HttpState)
-> Result<Response, NetworkError> {
// In the case of a WebSocket request, HTTP fetch is always used.
http_fetch(url, origin, headers, http_state)
}
// https://fetch.spec.whatwg.org/#concept-http-fetch
fn http_fetch(url: &ServoUrl,
origin: String,
headers: &mut Headers,
http_state: &HttpState)
-> Result<Response, NetworkError> {
// Step 1.
// Not applicable: with step 3 being useless here, this one is too.
// Step 2.
// Not applicable: we don't need to maintain an internal response.
// Step 3.
// Not applicable: request's service-workers mode is "none".
// Step 4.
// There cannot be a response yet at this point.
let mut response = {
// Step 4.1.
// Not applicable: CORS-preflight flag is unset.
// Step 4.2.
// Not applicable: request's redirect mode is "error".
// Step 4.3.
let response = http_network_or_cache_fetch(url, origin, headers, http_state);
// Step 4.4.
// Not applicable: CORS flag is unset.
response
};
// Step 5.
if response.as_ref().ok().map_or(false, |response| is_redirect_status(response.status)) {
// Step 5.1.
// Not applicable: the connection does not use HTTP/2.
// Steps 5.2-4.
// Not applicable: matters only if request's redirect mode is not "error".
// Step 5.5.
// Request's redirect mode is "error".
response = Err(NetworkError::Internal("Response should not be a redirection.".into()));
}
// Step 6.
response
}
// https://fetch.spec.whatwg.org/#concept-http-network-or-cache-fetch
fn http_network_or_cache_fetch(url: &ServoUrl,
origin: String,
headers: &mut Headers,
http_state: &HttpState)
-> Result<Response, NetworkError> {
// Steps 1-3.
// Not applicable: we don't even have a request yet, and there is no body
// in a WebSocket request.
// Step 4.
// Not applicable: credentials flag is always set
// because credentials mode is "include."
// Steps 5-9.
// Not applicable: there is no body in a WebSocket request.
// Step 10.
// TODO: handle header Referer.
// Step 11.
// Request's mode is "websocket".
headers.set(Origin(origin));
// Step 12.
// TODO: handle header User-Agent.
// Steps 13-14.
// Not applicable: request's cache mode is "no-store".
// Step 15.
{
// Step 15.1.
// We know there is no Pragma header yet.
headers.set(Pragma::NoCache);
// Step 15.2.
// We know there is no Cache-Control header yet.
headers.set(CacheControl(vec![CacheDirective::NoCache]));
}
// Step 16.
// TODO: handle Accept-Encoding.
// Not applicable: Connection header is already present.
// TODO: handle DNT.
headers.set(Host {
hostname: url.host_str().unwrap().to_owned(),
port: url.port(),
});
// Step 17.
// Credentials flag is set.
{
// Step 17.1.
// TODO: handle user agent configured to block cookies.
set_request_cookies(&url, headers, &http_state.cookie_jar);
// Steps 17.2-6.
// Not applicable: request has no Authorization header.
}
// Step 18.
// TODO: proxy-authentication entry.
// Step 19.
// Not applicable: with step 21 being useless, this one is too.
// Step 20.
// Not applicable: revalidatingFlag is only useful if step 21 is.
// Step 21.
// Not applicable: cache mode is "no-store".
// Step 22.
// There is no response yet.
let response = {
// Step 22.1.
// Not applicable: cache mode is "no-store".
// Step 22.2.
let forward_response = http_network_fetch(url, headers, http_state);
// Step 22.3.
// Not applicable: request's method is not unsafe.
// Step 22.4.
// Not applicable: revalidatingFlag is unset.
// Step 22.5.
// There is no response yet and the response should not be cached.
forward_response
};
// Step 23.
// TODO: handle 401 status when request's window is not "no-window".
// Step 24.
// TODO: handle 407 status when request's window is not "no-window".
// Step 25.
// Not applicable: authentication-fetch flag is unset.
// Step 26.
response
}
// https://fetch.spec.whatwg.org/#concept-http-network-fetch
fn http_network_fetch(url: &ServoUrl,
headers: &Headers,
http_state: &HttpState)
-> Result<Response, NetworkError> {
// Step 1.
// Not applicable: credentials flag is set.
// Steps 2-3.
// Request's mode is "websocket".
let connection = obtain_a_websocket_connection(url)?;
// Step 4.
// Not applicable: request’s body is null.
// Step 5.
let response = make_request(connection, url, headers)?;
// Steps 6-12.
// Not applicable: correct WebSocket responses don't have a body.
// Step 13.
// TODO: handle response's CSP list.
// Step 14.
// Not applicable: request's cache mode is "no-store".
// Step 15.
if let Some(cookies) = response.headers.get::<SetCookie>() {
let mut jar = http_state.cookie_jar.write().unwrap();
for cookie in &**cookies {
if let Some(cookie) = Cookie::from_cookie_string(cookie.clone(), url, CookieSource::HTTP) {
jar.push(cookie, url, CookieSource::HTTP);
}
}
}
// Step 16.
// Not applicable: correct WebSocket responses don't have a body.
// Step 17.
Ok(response)
}
fn make_request(mut stream: Stream,
url: &ServoUrl,
headers: &Headers)
-> Result<Response, NetworkError> {
write_request(&mut stream, url, headers).map_err(|e| {
NetworkError::Internal(format!("Request could not be sent: {}", e))
})?;
// FIXME: Stream isn't supposed to be cloned.
let writer = stream.clone();
// FIXME: BufReader from hyper isn't supposed to be used.
let
|
{
let _ = resource_event_sender.send(WebSocketNetworkEvent::ConnectionEstablished { protocol_in_use });
(sender, receiver)
}
|
conditional_block
|
websocket_loader.rs
|
Name, Upgrade};
use hyper::http::h1::{LINE_ENDING, parse_response};
use hyper::method::Method;
use hyper::net::HttpStream;
use hyper::status::StatusCode;
use hyper::version::HttpVersion;
use ipc_channel::ipc::{IpcReceiver, IpcSender};
use net_traits::{CookieSource, MessageData, NetworkError};
use net_traits::{WebSocketDomAction, WebSocketNetworkEvent};
use net_traits::request::{Destination, RequestInit, RequestMode};
use servo_url::ServoUrl;
use std::io::{self, Write};
use std::net::TcpStream;
use std::sync::{Arc, Mutex};
use std::sync::atomic::{AtomicBool, Ordering};
use std::thread;
use url::Position;
use websocket::Message;
use websocket::header::{Origin, WebSocketAccept, WebSocketKey, WebSocketProtocol, WebSocketVersion};
use websocket::message::OwnedMessage;
use websocket::receiver::{Reader as WsReader, Receiver as WsReceiver};
use websocket::sender::{Sender as WsSender, Writer as WsWriter};
use websocket::ws::dataframe::DataFrame;
pub fn init(
req_init: RequestInit,
resource_event_sender: IpcSender<WebSocketNetworkEvent>,
dom_action_receiver: IpcReceiver<WebSocketDomAction>,
http_state: Arc<HttpState>
) {
thread::Builder::new().name(format!("WebSocket connection to {}", req_init.url)).spawn(move || {
let channel = establish_a_websocket_connection(req_init, &http_state);
let (ws_sender, mut receiver) = match channel {
Ok((protocol_in_use, sender, receiver)) => {
let _ = resource_event_sender.send(WebSocketNetworkEvent::ConnectionEstablished { protocol_in_use });
(sender, receiver)
},
Err(e) => {
debug!("Failed to establish a WebSocket connection: {:?}", e);
let _ = resource_event_sender.send(WebSocketNetworkEvent::Fail);
return;
}
};
let initiated_close = Arc::new(AtomicBool::new(false));
let ws_sender = Arc::new(Mutex::new(ws_sender));
let initiated_close_incoming = initiated_close.clone();
let ws_sender_incoming = ws_sender.clone();
thread::spawn(move || {
for message in receiver.incoming_messages() {
let message = match message {
Ok(m) => m,
Err(e) => {
debug!("Error receiving incoming WebSocket message: {:?}", e);
let _ = resource_event_sender.send(WebSocketNetworkEvent::Fail);
break;
}
};
let message = match message {
OwnedMessage::Text(_) => {
MessageData::Text(String::from_utf8_lossy(&message.take_payload()).into_owned())
},
OwnedMessage::Binary(_) => MessageData::Binary(message.take_payload()),
OwnedMessage::Ping(_) => {
let pong = Message::pong(message.take_payload());
ws_sender_incoming.lock().unwrap().send_message(&pong).unwrap();
continue;
},
OwnedMessage::Pong(_) => continue,
OwnedMessage::Close(ref msg) => {
if!initiated_close_incoming.fetch_or(true, Ordering::SeqCst) {
ws_sender_incoming.lock().unwrap().send_message(&message).unwrap();
}
let (code, reason) = match *msg {
None => (None, "".into()),
Some(ref data) => (Some(data.status_code), data.reason.clone())
};
let _ = resource_event_sender.send(WebSocketNetworkEvent::Close(code, reason));
break;
},
};
let _ = resource_event_sender.send(WebSocketNetworkEvent::MessageReceived(message));
}
});
while let Ok(dom_action) = dom_action_receiver.recv() {
match dom_action {
WebSocketDomAction::SendMessage(MessageData::Text(data)) => {
ws_sender.lock().unwrap().send_message(&Message::text(data)).unwrap();
},
WebSocketDomAction::SendMessage(MessageData::Binary(data)) => {
ws_sender.lock().unwrap().send_message(&Message::binary(data)).unwrap();
},
WebSocketDomAction::Close(code, reason) => {
if!initiated_close.fetch_or(true, Ordering::SeqCst) {
let message = match code {
Some(code) => Message::close_because(code, reason.unwrap_or("".to_owned())),
None => Message::close()
};
ws_sender.lock().unwrap().send_message(&message).unwrap();
}
},
}
}
}).expect("Thread spawning failed");
}
type Stream = HttpStream;
// https://fetch.spec.whatwg.org/#concept-websocket-connection-obtain
fn obtain_a_websocket_connection(url: &ServoUrl) -> Result<Stream, NetworkError> {
// Step 1.
let host = url.host_str().unwrap();
// Step 2.
let port = url.port_or_known_default().unwrap();
// Step 3.
// We did not replace the scheme by "http" or "https" in step 1 of
// establish_a_websocket_connection.
let secure = match url.scheme() {
"ws" => false,
"wss" => true,
_ => panic!("URL's scheme should be ws or wss"),
};
if secure {
return Err(NetworkError::Internal("WSS is disabled for now.".into()));
}
// Steps 4-5.
let host = replace_host(host);
let tcp_stream = TcpStream::connect((&*host, port)).map_err(|e| {
NetworkError::Internal(format!("Could not connect to host: {}", e))
})?;
Ok(HttpStream(tcp_stream))
}
// https://fetch.spec.whatwg.org/#concept-websocket-establish
fn establish_a_websocket_connection(
req_init: RequestInit,
http_state: &HttpState
) -> Result<(Option<String>, WsWriter<HttpStream>, WsReader<HttpStream>), NetworkError>
{
let protocols = match req_init.mode {
RequestMode::WebSocket { protocols } => protocols.clone(),
_ => panic!("Received a RequestInit with a non-websocket mode in websocket_loader"),
};
// Steps 1 is not really applicable here, given we don't exactly go
// through the same infrastructure as the Fetch spec.
// Step 2, slimmed down because we don't go through the whole Fetch infra.
let mut headers = Headers::new();
// Step 3.
headers.set(Upgrade(vec![Protocol::new(ProtocolName::WebSocket, None)]));
// Step 4.
headers.set(Connection(vec![ConnectionOption::ConnectionHeader("upgrade".into())]));
// Step 5.
let key_value = WebSocketKey::new();
// Step 6.
headers.set(key_value);
// Step 7.
headers.set(WebSocketVersion::WebSocket13);
// Step 8.
if!protocols.is_empty() {
headers.set(WebSocketProtocol(protocols.clone()));
}
// Steps 9-10.
// TODO: handle permessage-deflate extension.
// Step 11 and network error check from step 12.
let response = fetch(req_init.url, req_init.origin.ascii_serialization(), headers, http_state)?;
// Step 12, the status code check.
if response.status!= StatusCode::SwitchingProtocols {
return Err(NetworkError::Internal("Response's status should be 101.".into()));
}
// Step 13.
if!protocols.is_empty() {
if response.headers.get::<WebSocketProtocol>().map_or(true, |protocols| protocols.is_empty()) {
return Err(NetworkError::Internal(
"Response's Sec-WebSocket-Protocol header is missing, malformed or empty.".into()));
}
}
// Step 14.2.
let upgrade_header = response.headers.get::<Upgrade>().ok_or_else(|| {
NetworkError::Internal("Response should have an Upgrade header.".into())
})?;
if upgrade_header.len()!= 1 {
return Err(NetworkError::Internal("Response's Upgrade header should have only one value.".into()));
}
if upgrade_header[0].name!= ProtocolName::WebSocket {
return Err(NetworkError::Internal("Response's Upgrade header value should be \"websocket\".".into()));
}
// Step 14.3.
let connection_header = response.headers.get::<Connection>().ok_or_else(|| {
NetworkError::Internal("Response should have a Connection header.".into())
})?;
let connection_includes_upgrade = connection_header.iter().any(|option| {
match *option {
ConnectionOption::ConnectionHeader(ref option) => *option == "upgrade",
_ => false,
}
});
if!connection_includes_upgrade {
return Err(NetworkError::Internal("Response's Connection header value should include \"upgrade\".".into()));
}
// Step 14.4.
let accept_header = response.headers.get::<WebSocketAccept>().ok_or_else(|| {
NetworkError::Internal("Response should have a Sec-Websocket-Accept header.".into())
})?;
if *accept_header!= WebSocketAccept::new(&key_value) {
return Err(NetworkError::Internal(
"Response's Sec-WebSocket-Accept header value did not match the sent key.".into()));
}
// Step 14.5.
// TODO: handle permessage-deflate extension.
// We don't support any extension, so we fail at the mere presence of
// a Sec-WebSocket-Extensions header.
if response.headers.get_raw("Sec-WebSocket-Extensions").is_some() {
return Err(NetworkError::Internal(
"Response's Sec-WebSocket-Extensions header value included unsupported extensions.".into()));
}
// Step 14.6.
let protocol_in_use = if let Some(response_protocols) = response.headers.get::<WebSocketProtocol>() {
for replied in &**response_protocols {
if!protocols.iter().any(|requested| requested.eq_ignore_ascii_case(replied)) {
return Err(NetworkError::Internal(
"Response's Sec-WebSocket-Protocols contain values that were not requested.".into()));
}
}
response_protocols.first().cloned()
} else {
None
};
let sender = WsSender::new(true);
let writer = WsWriter {
stream: response.writer,
sender
};
let receiver = WsReceiver::new(false);
let reader = WsReader {
stream: response.reader,
receiver,
};
Ok((protocol_in_use, writer, reader))
}
struct Response {
status: StatusCode,
headers: Headers,
reader: BufReader<Stream>,
writer: Stream,
}
// https://fetch.spec.whatwg.org/#concept-fetch
fn fetch(url: ServoUrl,
origin: String,
mut headers: Headers,
http_state: &HttpState)
-> Result<Response, NetworkError> {
// Step 1.
// TODO: handle request's window.
// Step 2.
// TODO: handle request's origin.
// Step 3.
set_default_accept(Destination::None, &mut headers);
// Step 4.
set_default_accept_language(&mut headers);
// Step 5.
// TODO: handle request's priority.
// Step 6.
// Not applicable: not a navigation request.
// Step 7.
// We know this is a subresource request.
{
// Step 7.1.
// Not applicable: client hints list is empty.
// Steps 7.2-3.
// TODO: handle fetch groups.
}
// Step 8.
main_fetch(url, origin, headers, http_state)
}
// https://fetch.spec.whatwg.org/#concept-main-fetch
fn main_fetch(url: ServoUrl,
origin: String,
mut headers: Headers,
http_state: &HttpState)
-> Result<Response, NetworkError> {
// Step 1.
let mut response = None;
// Step 2.
// Not applicable: request’s local-URLs-only flag is unset.
// Step 3.
// TODO: handle content security policy violations.
// Step 4.
// TODO: handle upgrade to a potentially secure URL.
// Step 5.
if should_be_blocked_due_to_bad_port(&url) {
response = Some(Err(NetworkError::Internal("Request should be blocked due to bad port.".into())));
}
// TODO: handle blocking as mixed content.
// TODO: handle blocking by content security policy.
// Steps 6-8.
// TODO: handle request's referrer policy.
// Step 9.
// Not applicable: request's current URL's scheme is not "ftp".
// Step 10.
// TODO: handle known HSTS host domain.
// Step 11.
// Not applicable: request's synchronous flag is set.
// Step 12.
let mut response = response.unwrap_or_else(|| {
// We must run the first sequence of substeps, given request's mode
// is "websocket".
// Step 12.1.
// Not applicable: the response is never exposed to the Web so it
// doesn't need to be filtered at all.
// Step 12.2.
scheme_fetch(&url, origin, &mut headers, http_state)
});
// Step 13.
// Not applicable: recursive flag is unset.
// Step 14.
// Not applicable: the response is never exposed to the Web so it doesn't
// need to be filtered at all.
// Steps 15-16.
// Not applicable: no need to maintain an internal response.
// Step 17.
if response.is_ok() {
// TODO: handle blocking as mixed content.
// TODO: handle blocking by content security policy.
// Not applicable: blocking due to MIME type matters only for scripts.
if should_be_blocked_due_to_nosniff(Destination::None, &headers) {
response = Err(NetworkError::Internal("Request should be blocked due to nosniff.".into()));
}
}
// Step 18.
// Not applicable: we don't care about the body at all.
// Step 19.
// Not applicable: request's integrity metadata is the empty string.
// Step 20.
// TODO: wait for response's body here, maybe?
response
}
// https://fetch.spec.whatwg.org/#concept-scheme-fetch
fn scheme_fetch(url: &ServoUrl,
origin: String,
headers: &mut Headers,
http_state: &HttpState)
-> Result<Response, NetworkError> {
// In the case of a WebSocket request, HTTP fetch is always used.
http_fetch(url, origin, headers, http_state)
}
// https://fetch.spec.whatwg.org/#concept-http-fetch
fn ht
|
rl: &ServoUrl,
origin: String,
headers: &mut Headers,
http_state: &HttpState)
-> Result<Response, NetworkError> {
// Step 1.
// Not applicable: with step 3 being useless here, this one is too.
// Step 2.
// Not applicable: we don't need to maintain an internal response.
// Step 3.
// Not applicable: request's service-workers mode is "none".
// Step 4.
// There cannot be a response yet at this point.
let mut response = {
// Step 4.1.
// Not applicable: CORS-preflight flag is unset.
// Step 4.2.
// Not applicable: request's redirect mode is "error".
// Step 4.3.
let response = http_network_or_cache_fetch(url, origin, headers, http_state);
// Step 4.4.
// Not applicable: CORS flag is unset.
response
};
// Step 5.
if response.as_ref().ok().map_or(false, |response| is_redirect_status(response.status)) {
// Step 5.1.
// Not applicable: the connection does not use HTTP/2.
// Steps 5.2-4.
// Not applicable: matters only if request's redirect mode is not "error".
// Step 5.5.
// Request's redirect mode is "error".
response = Err(NetworkError::Internal("Response should not be a redirection.".into()));
}
// Step 6.
response
}
// https://fetch.spec.whatwg.org/#concept-http-network-or-cache-fetch
fn http_network_or_cache_fetch(url: &ServoUrl,
origin: String,
headers: &mut Headers,
http_state: &HttpState)
-> Result<Response, NetworkError> {
// Steps 1-3.
// Not applicable: we don't even have a request yet, and there is no body
// in a WebSocket request.
// Step 4.
// Not applicable: credentials flag is always set
// because credentials mode is "include."
// Steps 5-9.
// Not applicable: there is no body in a WebSocket request.
// Step 10.
// TODO: handle header Referer.
// Step 11.
// Request's mode is "websocket".
headers.set(Origin(origin));
// Step 12.
// TODO: handle header User-Agent.
// Steps 13-14.
// Not applicable: request's cache mode is "no-store".
// Step 15.
{
// Step 15.1.
// We know there is no Pragma header yet.
headers.set(Pragma::NoCache);
// Step 15.2.
// We know there is no Cache-Control header yet.
headers.set(CacheControl(vec![CacheDirective::NoCache]));
}
// Step 16.
// TODO: handle Accept-Encoding.
// Not applicable: Connection header is already present.
// TODO: handle DNT.
headers.set(Host {
hostname: url.host_str().unwrap().to_owned(),
port: url.port(),
});
// Step 17.
// Credentials flag is set.
{
// Step 17.1.
// TODO: handle user agent configured to block cookies.
set_request_cookies(&url, headers, &http_state.cookie_jar);
// Steps 17.2-6.
// Not applicable: request has no Authorization header.
}
// Step 18.
// TODO: proxy-authentication entry.
// Step 19.
// Not applicable: with step 21 being useless, this one is too.
// Step 20.
// Not applicable: revalidatingFlag is only useful if step 21 is.
// Step 21.
// Not applicable: cache mode is "no-store".
// Step 22.
// There is no response yet.
let response = {
// Step 22.1.
// Not applicable: cache mode is "no-store".
// Step 22.2.
let forward_response = http_network_fetch(url, headers, http_state);
// Step 22.3.
// Not applicable: request's method is not unsafe.
// Step 22.4.
// Not applicable: revalidatingFlag is unset.
// Step 22.5.
// There is no response yet and the response should not be cached.
forward_response
};
// Step 23.
// TODO: handle 401 status when request's window is not "no-window".
// Step 24.
// TODO: handle 407 status when request's window is not "no-window".
// Step 25.
// Not applicable: authentication-fetch flag is unset.
// Step 26.
response
}
// https://fetch.spec.whatwg.org/#concept-http-network-fetch
fn http_network_fetch(url: &ServoUrl,
headers: &Headers,
http_state: &HttpState)
-> Result<Response, NetworkError> {
// Step 1.
// Not applicable: credentials flag is set.
// Steps 2-3.
// Request's mode is "websocket".
let connection = obtain_a_websocket_connection(url)?;
// Step 4.
// Not applicable: request’s body is null.
// Step 5.
let response = make_request(connection, url, headers)?;
// Steps 6-12.
// Not applicable: correct WebSocket responses don't have a body.
// Step 13.
// TODO: handle response's CSP list.
// Step 14.
// Not applicable: request's cache mode is "no-store".
// Step 15.
if let Some(cookies) = response.headers.get::<SetCookie>() {
let mut jar = http_state.cookie_jar.write().unwrap();
for cookie in &**cookies {
if let Some(cookie) = Cookie::from_cookie_string(cookie.clone(), url, CookieSource::HTTP) {
jar.push(cookie, url, CookieSource::HTTP);
}
}
}
// Step 16.
// Not applicable: correct WebSocket responses don't have a body.
// Step 17.
Ok(response)
}
fn make_request(mut stream: Stream,
url: &ServoUrl,
headers: &Headers)
-> Result<Response, NetworkError> {
write_request(&mut stream, url, headers).map_err(|e| {
NetworkError::Internal(format!("Request could not be sent: {}", e))
})?;
// FIXME: Stream isn't supposed to be cloned.
let writer = stream.clone();
// FIXME: BufReader from hyper isn't supposed to be used.
let
|
tp_fetch(u
|
identifier_name
|
websocket_loader.rs
|
std::sync::atomic::{AtomicBool, Ordering};
use std::thread;
use url::Position;
use websocket::Message;
use websocket::header::{Origin, WebSocketAccept, WebSocketKey, WebSocketProtocol, WebSocketVersion};
use websocket::message::OwnedMessage;
use websocket::receiver::{Reader as WsReader, Receiver as WsReceiver};
use websocket::sender::{Sender as WsSender, Writer as WsWriter};
use websocket::ws::dataframe::DataFrame;
pub fn init(
req_init: RequestInit,
resource_event_sender: IpcSender<WebSocketNetworkEvent>,
dom_action_receiver: IpcReceiver<WebSocketDomAction>,
http_state: Arc<HttpState>
) {
thread::Builder::new().name(format!("WebSocket connection to {}", req_init.url)).spawn(move || {
let channel = establish_a_websocket_connection(req_init, &http_state);
let (ws_sender, mut receiver) = match channel {
Ok((protocol_in_use, sender, receiver)) => {
let _ = resource_event_sender.send(WebSocketNetworkEvent::ConnectionEstablished { protocol_in_use });
(sender, receiver)
},
Err(e) => {
debug!("Failed to establish a WebSocket connection: {:?}", e);
let _ = resource_event_sender.send(WebSocketNetworkEvent::Fail);
return;
}
};
let initiated_close = Arc::new(AtomicBool::new(false));
let ws_sender = Arc::new(Mutex::new(ws_sender));
let initiated_close_incoming = initiated_close.clone();
let ws_sender_incoming = ws_sender.clone();
thread::spawn(move || {
for message in receiver.incoming_messages() {
let message = match message {
Ok(m) => m,
Err(e) => {
debug!("Error receiving incoming WebSocket message: {:?}", e);
let _ = resource_event_sender.send(WebSocketNetworkEvent::Fail);
break;
}
};
let message = match message {
OwnedMessage::Text(_) => {
MessageData::Text(String::from_utf8_lossy(&message.take_payload()).into_owned())
},
OwnedMessage::Binary(_) => MessageData::Binary(message.take_payload()),
OwnedMessage::Ping(_) => {
let pong = Message::pong(message.take_payload());
ws_sender_incoming.lock().unwrap().send_message(&pong).unwrap();
continue;
},
OwnedMessage::Pong(_) => continue,
OwnedMessage::Close(ref msg) => {
if!initiated_close_incoming.fetch_or(true, Ordering::SeqCst) {
ws_sender_incoming.lock().unwrap().send_message(&message).unwrap();
}
let (code, reason) = match *msg {
None => (None, "".into()),
Some(ref data) => (Some(data.status_code), data.reason.clone())
};
let _ = resource_event_sender.send(WebSocketNetworkEvent::Close(code, reason));
break;
},
};
let _ = resource_event_sender.send(WebSocketNetworkEvent::MessageReceived(message));
}
});
while let Ok(dom_action) = dom_action_receiver.recv() {
match dom_action {
WebSocketDomAction::SendMessage(MessageData::Text(data)) => {
ws_sender.lock().unwrap().send_message(&Message::text(data)).unwrap();
},
WebSocketDomAction::SendMessage(MessageData::Binary(data)) => {
ws_sender.lock().unwrap().send_message(&Message::binary(data)).unwrap();
},
WebSocketDomAction::Close(code, reason) => {
if!initiated_close.fetch_or(true, Ordering::SeqCst) {
let message = match code {
Some(code) => Message::close_because(code, reason.unwrap_or("".to_owned())),
None => Message::close()
};
ws_sender.lock().unwrap().send_message(&message).unwrap();
}
},
}
}
}).expect("Thread spawning failed");
}
type Stream = HttpStream;
// https://fetch.spec.whatwg.org/#concept-websocket-connection-obtain
fn obtain_a_websocket_connection(url: &ServoUrl) -> Result<Stream, NetworkError> {
// Step 1.
let host = url.host_str().unwrap();
// Step 2.
let port = url.port_or_known_default().unwrap();
// Step 3.
// We did not replace the scheme by "http" or "https" in step 1 of
// establish_a_websocket_connection.
let secure = match url.scheme() {
"ws" => false,
"wss" => true,
_ => panic!("URL's scheme should be ws or wss"),
};
if secure {
return Err(NetworkError::Internal("WSS is disabled for now.".into()));
}
// Steps 4-5.
let host = replace_host(host);
let tcp_stream = TcpStream::connect((&*host, port)).map_err(|e| {
NetworkError::Internal(format!("Could not connect to host: {}", e))
})?;
Ok(HttpStream(tcp_stream))
}
// https://fetch.spec.whatwg.org/#concept-websocket-establish
fn establish_a_websocket_connection(
req_init: RequestInit,
http_state: &HttpState
) -> Result<(Option<String>, WsWriter<HttpStream>, WsReader<HttpStream>), NetworkError>
{
let protocols = match req_init.mode {
RequestMode::WebSocket { protocols } => protocols.clone(),
_ => panic!("Received a RequestInit with a non-websocket mode in websocket_loader"),
};
// Steps 1 is not really applicable here, given we don't exactly go
// through the same infrastructure as the Fetch spec.
// Step 2, slimmed down because we don't go through the whole Fetch infra.
let mut headers = Headers::new();
// Step 3.
headers.set(Upgrade(vec![Protocol::new(ProtocolName::WebSocket, None)]));
// Step 4.
headers.set(Connection(vec![ConnectionOption::ConnectionHeader("upgrade".into())]));
// Step 5.
let key_value = WebSocketKey::new();
// Step 6.
headers.set(key_value);
// Step 7.
headers.set(WebSocketVersion::WebSocket13);
// Step 8.
if!protocols.is_empty() {
headers.set(WebSocketProtocol(protocols.clone()));
}
// Steps 9-10.
// TODO: handle permessage-deflate extension.
// Step 11 and network error check from step 12.
let response = fetch(req_init.url, req_init.origin.ascii_serialization(), headers, http_state)?;
// Step 12, the status code check.
if response.status!= StatusCode::SwitchingProtocols {
return Err(NetworkError::Internal("Response's status should be 101.".into()));
}
// Step 13.
if!protocols.is_empty() {
if response.headers.get::<WebSocketProtocol>().map_or(true, |protocols| protocols.is_empty()) {
return Err(NetworkError::Internal(
"Response's Sec-WebSocket-Protocol header is missing, malformed or empty.".into()));
}
}
// Step 14.2.
let upgrade_header = response.headers.get::<Upgrade>().ok_or_else(|| {
NetworkError::Internal("Response should have an Upgrade header.".into())
})?;
if upgrade_header.len()!= 1 {
return Err(NetworkError::Internal("Response's Upgrade header should have only one value.".into()));
}
if upgrade_header[0].name!= ProtocolName::WebSocket {
return Err(NetworkError::Internal("Response's Upgrade header value should be \"websocket\".".into()));
}
// Step 14.3.
let connection_header = response.headers.get::<Connection>().ok_or_else(|| {
NetworkError::Internal("Response should have a Connection header.".into())
})?;
let connection_includes_upgrade = connection_header.iter().any(|option| {
match *option {
ConnectionOption::ConnectionHeader(ref option) => *option == "upgrade",
_ => false,
}
});
if!connection_includes_upgrade {
return Err(NetworkError::Internal("Response's Connection header value should include \"upgrade\".".into()));
}
// Step 14.4.
let accept_header = response.headers.get::<WebSocketAccept>().ok_or_else(|| {
NetworkError::Internal("Response should have a Sec-Websocket-Accept header.".into())
})?;
if *accept_header!= WebSocketAccept::new(&key_value) {
return Err(NetworkError::Internal(
"Response's Sec-WebSocket-Accept header value did not match the sent key.".into()));
}
// Step 14.5.
// TODO: handle permessage-deflate extension.
// We don't support any extension, so we fail at the mere presence of
// a Sec-WebSocket-Extensions header.
if response.headers.get_raw("Sec-WebSocket-Extensions").is_some() {
return Err(NetworkError::Internal(
"Response's Sec-WebSocket-Extensions header value included unsupported extensions.".into()));
}
// Step 14.6.
let protocol_in_use = if let Some(response_protocols) = response.headers.get::<WebSocketProtocol>() {
for replied in &**response_protocols {
if!protocols.iter().any(|requested| requested.eq_ignore_ascii_case(replied)) {
return Err(NetworkError::Internal(
"Response's Sec-WebSocket-Protocols contain values that were not requested.".into()));
}
}
response_protocols.first().cloned()
} else {
None
};
let sender = WsSender::new(true);
let writer = WsWriter {
stream: response.writer,
sender
};
let receiver = WsReceiver::new(false);
let reader = WsReader {
stream: response.reader,
receiver,
};
Ok((protocol_in_use, writer, reader))
}
struct Response {
status: StatusCode,
headers: Headers,
reader: BufReader<Stream>,
writer: Stream,
}
// https://fetch.spec.whatwg.org/#concept-fetch
fn fetch(url: ServoUrl,
origin: String,
mut headers: Headers,
http_state: &HttpState)
-> Result<Response, NetworkError> {
// Step 1.
// TODO: handle request's window.
// Step 2.
// TODO: handle request's origin.
// Step 3.
set_default_accept(Destination::None, &mut headers);
// Step 4.
set_default_accept_language(&mut headers);
// Step 5.
// TODO: handle request's priority.
// Step 6.
// Not applicable: not a navigation request.
// Step 7.
// We know this is a subresource request.
{
// Step 7.1.
// Not applicable: client hints list is empty.
// Steps 7.2-3.
// TODO: handle fetch groups.
}
// Step 8.
main_fetch(url, origin, headers, http_state)
}
// https://fetch.spec.whatwg.org/#concept-main-fetch
fn main_fetch(url: ServoUrl,
origin: String,
mut headers: Headers,
http_state: &HttpState)
-> Result<Response, NetworkError> {
// Step 1.
let mut response = None;
// Step 2.
// Not applicable: request’s local-URLs-only flag is unset.
// Step 3.
// TODO: handle content security policy violations.
// Step 4.
// TODO: handle upgrade to a potentially secure URL.
// Step 5.
if should_be_blocked_due_to_bad_port(&url) {
response = Some(Err(NetworkError::Internal("Request should be blocked due to bad port.".into())));
}
// TODO: handle blocking as mixed content.
// TODO: handle blocking by content security policy.
// Steps 6-8.
// TODO: handle request's referrer policy.
// Step 9.
// Not applicable: request's current URL's scheme is not "ftp".
// Step 10.
// TODO: handle known HSTS host domain.
// Step 11.
// Not applicable: request's synchronous flag is set.
// Step 12.
let mut response = response.unwrap_or_else(|| {
// We must run the first sequence of substeps, given request's mode
// is "websocket".
// Step 12.1.
// Not applicable: the response is never exposed to the Web so it
// doesn't need to be filtered at all.
// Step 12.2.
scheme_fetch(&url, origin, &mut headers, http_state)
});
// Step 13.
// Not applicable: recursive flag is unset.
// Step 14.
// Not applicable: the response is never exposed to the Web so it doesn't
// need to be filtered at all.
// Steps 15-16.
// Not applicable: no need to maintain an internal response.
// Step 17.
if response.is_ok() {
// TODO: handle blocking as mixed content.
// TODO: handle blocking by content security policy.
// Not applicable: blocking due to MIME type matters only for scripts.
if should_be_blocked_due_to_nosniff(Destination::None, &headers) {
response = Err(NetworkError::Internal("Request should be blocked due to nosniff.".into()));
}
}
// Step 18.
// Not applicable: we don't care about the body at all.
// Step 19.
// Not applicable: request's integrity metadata is the empty string.
// Step 20.
// TODO: wait for response's body here, maybe?
response
}
// https://fetch.spec.whatwg.org/#concept-scheme-fetch
fn scheme_fetch(url: &ServoUrl,
origin: String,
headers: &mut Headers,
http_state: &HttpState)
-> Result<Response, NetworkError> {
// In the case of a WebSocket request, HTTP fetch is always used.
http_fetch(url, origin, headers, http_state)
}
// https://fetch.spec.whatwg.org/#concept-http-fetch
fn http_fetch(url: &ServoUrl,
origin: String,
headers: &mut Headers,
http_state: &HttpState)
-> Result<Response, NetworkError> {
// Step 1.
// Not applicable: with step 3 being useless here, this one is too.
// Step 2.
// Not applicable: we don't need to maintain an internal response.
// Step 3.
// Not applicable: request's service-workers mode is "none".
// Step 4.
// There cannot be a response yet at this point.
let mut response = {
// Step 4.1.
// Not applicable: CORS-preflight flag is unset.
// Step 4.2.
// Not applicable: request's redirect mode is "error".
// Step 4.3.
let response = http_network_or_cache_fetch(url, origin, headers, http_state);
// Step 4.4.
// Not applicable: CORS flag is unset.
response
};
// Step 5.
if response.as_ref().ok().map_or(false, |response| is_redirect_status(response.status)) {
// Step 5.1.
// Not applicable: the connection does not use HTTP/2.
// Steps 5.2-4.
// Not applicable: matters only if request's redirect mode is not "error".
// Step 5.5.
// Request's redirect mode is "error".
response = Err(NetworkError::Internal("Response should not be a redirection.".into()));
}
// Step 6.
response
}
// https://fetch.spec.whatwg.org/#concept-http-network-or-cache-fetch
fn http_network_or_cache_fetch(url: &ServoUrl,
origin: String,
headers: &mut Headers,
http_state: &HttpState)
-> Result<Response, NetworkError> {
// Steps 1-3.
// Not applicable: we don't even have a request yet, and there is no body
// in a WebSocket request.
// Step 4.
// Not applicable: credentials flag is always set
// because credentials mode is "include."
// Steps 5-9.
// Not applicable: there is no body in a WebSocket request.
// Step 10.
// TODO: handle header Referer.
// Step 11.
// Request's mode is "websocket".
headers.set(Origin(origin));
// Step 12.
// TODO: handle header User-Agent.
// Steps 13-14.
// Not applicable: request's cache mode is "no-store".
// Step 15.
{
// Step 15.1.
// We know there is no Pragma header yet.
headers.set(Pragma::NoCache);
// Step 15.2.
// We know there is no Cache-Control header yet.
headers.set(CacheControl(vec![CacheDirective::NoCache]));
}
// Step 16.
// TODO: handle Accept-Encoding.
// Not applicable: Connection header is already present.
// TODO: handle DNT.
headers.set(Host {
hostname: url.host_str().unwrap().to_owned(),
port: url.port(),
});
// Step 17.
// Credentials flag is set.
{
// Step 17.1.
// TODO: handle user agent configured to block cookies.
set_request_cookies(&url, headers, &http_state.cookie_jar);
// Steps 17.2-6.
// Not applicable: request has no Authorization header.
}
// Step 18.
// TODO: proxy-authentication entry.
// Step 19.
// Not applicable: with step 21 being useless, this one is too.
// Step 20.
// Not applicable: revalidatingFlag is only useful if step 21 is.
// Step 21.
// Not applicable: cache mode is "no-store".
// Step 22.
// There is no response yet.
let response = {
// Step 22.1.
// Not applicable: cache mode is "no-store".
// Step 22.2.
let forward_response = http_network_fetch(url, headers, http_state);
// Step 22.3.
// Not applicable: request's method is not unsafe.
// Step 22.4.
// Not applicable: revalidatingFlag is unset.
// Step 22.5.
// There is no response yet and the response should not be cached.
forward_response
};
// Step 23.
// TODO: handle 401 status when request's window is not "no-window".
// Step 24.
// TODO: handle 407 status when request's window is not "no-window".
// Step 25.
// Not applicable: authentication-fetch flag is unset.
// Step 26.
response
}
// https://fetch.spec.whatwg.org/#concept-http-network-fetch
fn http_network_fetch(url: &ServoUrl,
headers: &Headers,
http_state: &HttpState)
-> Result<Response, NetworkError> {
// Step 1.
// Not applicable: credentials flag is set.
// Steps 2-3.
// Request's mode is "websocket".
let connection = obtain_a_websocket_connection(url)?;
// Step 4.
// Not applicable: request’s body is null.
// Step 5.
let response = make_request(connection, url, headers)?;
// Steps 6-12.
// Not applicable: correct WebSocket responses don't have a body.
// Step 13.
// TODO: handle response's CSP list.
// Step 14.
// Not applicable: request's cache mode is "no-store".
// Step 15.
if let Some(cookies) = response.headers.get::<SetCookie>() {
let mut jar = http_state.cookie_jar.write().unwrap();
for cookie in &**cookies {
if let Some(cookie) = Cookie::from_cookie_string(cookie.clone(), url, CookieSource::HTTP) {
jar.push(cookie, url, CookieSource::HTTP);
}
}
}
// Step 16.
// Not applicable: correct WebSocket responses don't have a body.
// Step 17.
Ok(response)
}
fn make_request(mut stream: Stream,
url: &ServoUrl,
headers: &Headers)
-> Result<Response, NetworkError> {
write_request(&mut stream, url, headers).map_err(|e| {
NetworkError::Internal(format!("Request could not be sent: {}", e))
})?;
// FIXME: Stream isn't supposed to be cloned.
let writer = stream.clone();
// FIXME: BufReader from hyper isn't supposed to be used.
let mut reader = BufReader::new(stream);
let head = parse_response(&mut reader).map_err(|e| {
NetworkError::Internal(format!("Response could not be read: {}", e))
})?;
// This isn't in the spec, but this is the correct thing to do for WebSocket requests.
if head.version!= HttpVersion::Http11 {
return Err(NetworkError::Internal("Response's HTTP version should be HTTP/1.1.".into()));
|
}
// FIXME: StatusCode::from_u16 isn't supposed to be used.
|
random_line_split
|
|
websocket_loader.rs
|
ProtocolName, Upgrade};
use hyper::http::h1::{LINE_ENDING, parse_response};
use hyper::method::Method;
use hyper::net::HttpStream;
use hyper::status::StatusCode;
use hyper::version::HttpVersion;
use ipc_channel::ipc::{IpcReceiver, IpcSender};
use net_traits::{CookieSource, MessageData, NetworkError};
use net_traits::{WebSocketDomAction, WebSocketNetworkEvent};
use net_traits::request::{Destination, RequestInit, RequestMode};
use servo_url::ServoUrl;
use std::io::{self, Write};
use std::net::TcpStream;
use std::sync::{Arc, Mutex};
use std::sync::atomic::{AtomicBool, Ordering};
use std::thread;
use url::Position;
use websocket::Message;
use websocket::header::{Origin, WebSocketAccept, WebSocketKey, WebSocketProtocol, WebSocketVersion};
use websocket::message::OwnedMessage;
use websocket::receiver::{Reader as WsReader, Receiver as WsReceiver};
use websocket::sender::{Sender as WsSender, Writer as WsWriter};
use websocket::ws::dataframe::DataFrame;
pub fn init(
req_init: RequestInit,
resource_event_sender: IpcSender<WebSocketNetworkEvent>,
dom_action_receiver: IpcReceiver<WebSocketDomAction>,
http_state: Arc<HttpState>
) {
thread::Builder::new().name(format!("WebSocket connection to {}", req_init.url)).spawn(move || {
let channel = establish_a_websocket_connection(req_init, &http_state);
let (ws_sender, mut receiver) = match channel {
Ok((protocol_in_use, sender, receiver)) => {
let _ = resource_event_sender.send(WebSocketNetworkEvent::ConnectionEstablished { protocol_in_use });
(sender, receiver)
},
Err(e) => {
debug!("Failed to establish a WebSocket connection: {:?}", e);
let _ = resource_event_sender.send(WebSocketNetworkEvent::Fail);
return;
}
};
let initiated_close = Arc::new(AtomicBool::new(false));
let ws_sender = Arc::new(Mutex::new(ws_sender));
let initiated_close_incoming = initiated_close.clone();
let ws_sender_incoming = ws_sender.clone();
thread::spawn(move || {
for message in receiver.incoming_messages() {
let message = match message {
Ok(m) => m,
Err(e) => {
debug!("Error receiving incoming WebSocket message: {:?}", e);
let _ = resource_event_sender.send(WebSocketNetworkEvent::Fail);
break;
}
};
let message = match message {
OwnedMessage::Text(_) => {
MessageData::Text(String::from_utf8_lossy(&message.take_payload()).into_owned())
},
OwnedMessage::Binary(_) => MessageData::Binary(message.take_payload()),
OwnedMessage::Ping(_) => {
let pong = Message::pong(message.take_payload());
ws_sender_incoming.lock().unwrap().send_message(&pong).unwrap();
continue;
},
OwnedMessage::Pong(_) => continue,
OwnedMessage::Close(ref msg) => {
if!initiated_close_incoming.fetch_or(true, Ordering::SeqCst) {
ws_sender_incoming.lock().unwrap().send_message(&message).unwrap();
}
let (code, reason) = match *msg {
None => (None, "".into()),
Some(ref data) => (Some(data.status_code), data.reason.clone())
};
let _ = resource_event_sender.send(WebSocketNetworkEvent::Close(code, reason));
break;
},
};
let _ = resource_event_sender.send(WebSocketNetworkEvent::MessageReceived(message));
}
});
while let Ok(dom_action) = dom_action_receiver.recv() {
match dom_action {
WebSocketDomAction::SendMessage(MessageData::Text(data)) => {
ws_sender.lock().unwrap().send_message(&Message::text(data)).unwrap();
},
WebSocketDomAction::SendMessage(MessageData::Binary(data)) => {
ws_sender.lock().unwrap().send_message(&Message::binary(data)).unwrap();
},
WebSocketDomAction::Close(code, reason) => {
if!initiated_close.fetch_or(true, Ordering::SeqCst) {
let message = match code {
Some(code) => Message::close_because(code, reason.unwrap_or("".to_owned())),
None => Message::close()
};
ws_sender.lock().unwrap().send_message(&message).unwrap();
}
},
}
}
}).expect("Thread spawning failed");
}
type Stream = HttpStream;
// https://fetch.spec.whatwg.org/#concept-websocket-connection-obtain
fn obtain_a_websocket_connection(url: &ServoUrl) -> Result<Stream, NetworkError> {
// Step 1.
let host = url.host_str().unwrap();
// Step 2.
let port = url.port_or_known_default().unwrap();
// Step 3.
// We did not replace the scheme by "http" or "https" in step 1 of
// establish_a_websocket_connection.
let secure = match url.scheme() {
"ws" => false,
"wss" => true,
_ => panic!("URL's scheme should be ws or wss"),
};
if secure {
return Err(NetworkError::Internal("WSS is disabled for now.".into()));
}
// Steps 4-5.
let host = replace_host(host);
let tcp_stream = TcpStream::connect((&*host, port)).map_err(|e| {
NetworkError::Internal(format!("Could not connect to host: {}", e))
})?;
Ok(HttpStream(tcp_stream))
}
// https://fetch.spec.whatwg.org/#concept-websocket-establish
fn establish_a_websocket_connection(
req_init: RequestInit,
http_state: &HttpState
) -> Result<(Option<String>, WsWriter<HttpStream>, WsReader<HttpStream>), NetworkError>
{
let protocols = match req_init.mode {
RequestMode::WebSocket { protocols } => protocols.clone(),
_ => panic!("Received a RequestInit with a non-websocket mode in websocket_loader"),
};
// Steps 1 is not really applicable here, given we don't exactly go
// through the same infrastructure as the Fetch spec.
// Step 2, slimmed down because we don't go through the whole Fetch infra.
let mut headers = Headers::new();
// Step 3.
headers.set(Upgrade(vec![Protocol::new(ProtocolName::WebSocket, None)]));
// Step 4.
headers.set(Connection(vec![ConnectionOption::ConnectionHeader("upgrade".into())]));
// Step 5.
let key_value = WebSocketKey::new();
// Step 6.
headers.set(key_value);
// Step 7.
headers.set(WebSocketVersion::WebSocket13);
// Step 8.
if!protocols.is_empty() {
headers.set(WebSocketProtocol(protocols.clone()));
}
// Steps 9-10.
// TODO: handle permessage-deflate extension.
// Step 11 and network error check from step 12.
let response = fetch(req_init.url, req_init.origin.ascii_serialization(), headers, http_state)?;
// Step 12, the status code check.
if response.status!= StatusCode::SwitchingProtocols {
return Err(NetworkError::Internal("Response's status should be 101.".into()));
}
// Step 13.
if!protocols.is_empty() {
if response.headers.get::<WebSocketProtocol>().map_or(true, |protocols| protocols.is_empty()) {
return Err(NetworkError::Internal(
"Response's Sec-WebSocket-Protocol header is missing, malformed or empty.".into()));
}
}
// Step 14.2.
let upgrade_header = response.headers.get::<Upgrade>().ok_or_else(|| {
NetworkError::Internal("Response should have an Upgrade header.".into())
})?;
if upgrade_header.len()!= 1 {
return Err(NetworkError::Internal("Response's Upgrade header should have only one value.".into()));
}
if upgrade_header[0].name!= ProtocolName::WebSocket {
return Err(NetworkError::Internal("Response's Upgrade header value should be \"websocket\".".into()));
}
// Step 14.3.
let connection_header = response.headers.get::<Connection>().ok_or_else(|| {
NetworkError::Internal("Response should have a Connection header.".into())
})?;
let connection_includes_upgrade = connection_header.iter().any(|option| {
match *option {
ConnectionOption::ConnectionHeader(ref option) => *option == "upgrade",
_ => false,
}
});
if!connection_includes_upgrade {
return Err(NetworkError::Internal("Response's Connection header value should include \"upgrade\".".into()));
}
// Step 14.4.
let accept_header = response.headers.get::<WebSocketAccept>().ok_or_else(|| {
NetworkError::Internal("Response should have a Sec-Websocket-Accept header.".into())
})?;
if *accept_header!= WebSocketAccept::new(&key_value) {
return Err(NetworkError::Internal(
"Response's Sec-WebSocket-Accept header value did not match the sent key.".into()));
}
// Step 14.5.
// TODO: handle permessage-deflate extension.
// We don't support any extension, so we fail at the mere presence of
// a Sec-WebSocket-Extensions header.
if response.headers.get_raw("Sec-WebSocket-Extensions").is_some() {
return Err(NetworkError::Internal(
"Response's Sec-WebSocket-Extensions header value included unsupported extensions.".into()));
}
// Step 14.6.
let protocol_in_use = if let Some(response_protocols) = response.headers.get::<WebSocketProtocol>() {
for replied in &**response_protocols {
if!protocols.iter().any(|requested| requested.eq_ignore_ascii_case(replied)) {
return Err(NetworkError::Internal(
"Response's Sec-WebSocket-Protocols contain values that were not requested.".into()));
}
}
response_protocols.first().cloned()
} else {
None
};
let sender = WsSender::new(true);
let writer = WsWriter {
stream: response.writer,
sender
};
let receiver = WsReceiver::new(false);
let reader = WsReader {
stream: response.reader,
receiver,
};
Ok((protocol_in_use, writer, reader))
}
struct Response {
status: StatusCode,
headers: Headers,
reader: BufReader<Stream>,
writer: Stream,
}
// https://fetch.spec.whatwg.org/#concept-fetch
fn fetch(url: ServoUrl,
origin: String,
mut headers: Headers,
http_state: &HttpState)
-> Result<Response, NetworkError> {
// Step 1.
// TODO: handle request's window.
// Step 2.
// TODO: handle request's origin.
// Step 3.
set_default_accept(Destination::None, &mut headers);
// Step 4.
set_default_accept_language(&mut headers);
// Step 5.
// TODO: handle request's priority.
// Step 6.
// Not applicable: not a navigation request.
// Step 7.
// We know this is a subresource request.
{
// Step 7.1.
// Not applicable: client hints list is empty.
// Steps 7.2-3.
// TODO: handle fetch groups.
}
// Step 8.
main_fetch(url, origin, headers, http_state)
}
// https://fetch.spec.whatwg.org/#concept-main-fetch
fn main_fetch(url: ServoUrl,
origin: String,
mut headers: Headers,
http_state: &HttpState)
-> Result<Response, NetworkError> {
// Step 1.
let mut response = None;
// Step 2.
// Not applicable: request’s local-URLs-only flag is unset.
// Step 3.
// TODO: handle content security policy violations.
// Step 4.
// TODO: handle upgrade to a potentially secure URL.
// Step 5.
if should_be_blocked_due_to_bad_port(&url) {
response = Some(Err(NetworkError::Internal("Request should be blocked due to bad port.".into())));
}
// TODO: handle blocking as mixed content.
// TODO: handle blocking by content security policy.
// Steps 6-8.
// TODO: handle request's referrer policy.
// Step 9.
// Not applicable: request's current URL's scheme is not "ftp".
// Step 10.
// TODO: handle known HSTS host domain.
// Step 11.
// Not applicable: request's synchronous flag is set.
// Step 12.
let mut response = response.unwrap_or_else(|| {
// We must run the first sequence of substeps, given request's mode
// is "websocket".
// Step 12.1.
// Not applicable: the response is never exposed to the Web so it
// doesn't need to be filtered at all.
// Step 12.2.
scheme_fetch(&url, origin, &mut headers, http_state)
});
// Step 13.
// Not applicable: recursive flag is unset.
// Step 14.
// Not applicable: the response is never exposed to the Web so it doesn't
// need to be filtered at all.
// Steps 15-16.
// Not applicable: no need to maintain an internal response.
// Step 17.
if response.is_ok() {
// TODO: handle blocking as mixed content.
// TODO: handle blocking by content security policy.
// Not applicable: blocking due to MIME type matters only for scripts.
if should_be_blocked_due_to_nosniff(Destination::None, &headers) {
response = Err(NetworkError::Internal("Request should be blocked due to nosniff.".into()));
}
}
// Step 18.
// Not applicable: we don't care about the body at all.
// Step 19.
// Not applicable: request's integrity metadata is the empty string.
// Step 20.
// TODO: wait for response's body here, maybe?
response
}
// https://fetch.spec.whatwg.org/#concept-scheme-fetch
fn scheme_fetch(url: &ServoUrl,
origin: String,
headers: &mut Headers,
http_state: &HttpState)
-> Result<Response, NetworkError> {
// In the case of a WebSocket request, HTTP fetch is always used.
http_fetch(url, origin, headers, http_state)
}
// https://fetch.spec.whatwg.org/#concept-http-fetch
fn http_fetch(url: &ServoUrl,
origin: String,
headers: &mut Headers,
http_state: &HttpState)
-> Result<Response, NetworkError> {
|
// Step 4.4.
// Not applicable: CORS flag is unset.
response
};
// Step 5.
if response.as_ref().ok().map_or(false, |response| is_redirect_status(response.status)) {
// Step 5.1.
// Not applicable: the connection does not use HTTP/2.
// Steps 5.2-4.
// Not applicable: matters only if request's redirect mode is not "error".
// Step 5.5.
// Request's redirect mode is "error".
response = Err(NetworkError::Internal("Response should not be a redirection.".into()));
}
// Step 6.
response
}
// https://fetch.spec.whatwg.org/#concept-http-network-or-cache-fetch
fn http_network_or_cache_fetch(url: &ServoUrl,
origin: String,
headers: &mut Headers,
http_state: &HttpState)
-> Result<Response, NetworkError> {
// Steps 1-3.
// Not applicable: we don't even have a request yet, and there is no body
// in a WebSocket request.
// Step 4.
// Not applicable: credentials flag is always set
// because credentials mode is "include."
// Steps 5-9.
// Not applicable: there is no body in a WebSocket request.
// Step 10.
// TODO: handle header Referer.
// Step 11.
// Request's mode is "websocket".
headers.set(Origin(origin));
// Step 12.
// TODO: handle header User-Agent.
// Steps 13-14.
// Not applicable: request's cache mode is "no-store".
// Step 15.
{
// Step 15.1.
// We know there is no Pragma header yet.
headers.set(Pragma::NoCache);
// Step 15.2.
// We know there is no Cache-Control header yet.
headers.set(CacheControl(vec![CacheDirective::NoCache]));
}
// Step 16.
// TODO: handle Accept-Encoding.
// Not applicable: Connection header is already present.
// TODO: handle DNT.
headers.set(Host {
hostname: url.host_str().unwrap().to_owned(),
port: url.port(),
});
// Step 17.
// Credentials flag is set.
{
// Step 17.1.
// TODO: handle user agent configured to block cookies.
set_request_cookies(&url, headers, &http_state.cookie_jar);
// Steps 17.2-6.
// Not applicable: request has no Authorization header.
}
// Step 18.
// TODO: proxy-authentication entry.
// Step 19.
// Not applicable: with step 21 being useless, this one is too.
// Step 20.
// Not applicable: revalidatingFlag is only useful if step 21 is.
// Step 21.
// Not applicable: cache mode is "no-store".
// Step 22.
// There is no response yet.
let response = {
// Step 22.1.
// Not applicable: cache mode is "no-store".
// Step 22.2.
let forward_response = http_network_fetch(url, headers, http_state);
// Step 22.3.
// Not applicable: request's method is not unsafe.
// Step 22.4.
// Not applicable: revalidatingFlag is unset.
// Step 22.5.
// There is no response yet and the response should not be cached.
forward_response
};
// Step 23.
// TODO: handle 401 status when request's window is not "no-window".
// Step 24.
// TODO: handle 407 status when request's window is not "no-window".
// Step 25.
// Not applicable: authentication-fetch flag is unset.
// Step 26.
response
}
// https://fetch.spec.whatwg.org/#concept-http-network-fetch
fn http_network_fetch(url: &ServoUrl,
headers: &Headers,
http_state: &HttpState)
-> Result<Response, NetworkError> {
// Step 1.
// Not applicable: credentials flag is set.
// Steps 2-3.
// Request's mode is "websocket".
let connection = obtain_a_websocket_connection(url)?;
// Step 4.
// Not applicable: request’s body is null.
// Step 5.
let response = make_request(connection, url, headers)?;
// Steps 6-12.
// Not applicable: correct WebSocket responses don't have a body.
// Step 13.
// TODO: handle response's CSP list.
// Step 14.
// Not applicable: request's cache mode is "no-store".
// Step 15.
if let Some(cookies) = response.headers.get::<SetCookie>() {
let mut jar = http_state.cookie_jar.write().unwrap();
for cookie in &**cookies {
if let Some(cookie) = Cookie::from_cookie_string(cookie.clone(), url, CookieSource::HTTP) {
jar.push(cookie, url, CookieSource::HTTP);
}
}
}
// Step 16.
// Not applicable: correct WebSocket responses don't have a body.
// Step 17.
Ok(response)
}
fn make_request(mut stream: Stream,
url: &ServoUrl,
headers: &Headers)
-> Result<Response, NetworkError> {
write_request(&mut stream, url, headers).map_err(|e| {
NetworkError::Internal(format!("Request could not be sent: {}", e))
})?;
// FIXME: Stream isn't supposed to be cloned.
let writer = stream.clone();
// FIXME: BufReader from hyper isn't supposed to be used.
let mut reader
|
// Step 1.
// Not applicable: with step 3 being useless here, this one is too.
// Step 2.
// Not applicable: we don't need to maintain an internal response.
// Step 3.
// Not applicable: request's service-workers mode is "none".
// Step 4.
// There cannot be a response yet at this point.
let mut response = {
// Step 4.1.
// Not applicable: CORS-preflight flag is unset.
// Step 4.2.
// Not applicable: request's redirect mode is "error".
// Step 4.3.
let response = http_network_or_cache_fetch(url, origin, headers, http_state);
|
identifier_body
|
sized_unsized_cast.rs
|
use crate::structured_errors::StructuredDiagnostic;
use rustc_errors::{DiagnosticBuilder, DiagnosticId};
use rustc_middle::ty::{Ty, TypeFoldable};
use rustc_session::Session;
use rustc_span::Span;
pub struct SizedUnsizedCast<'tcx> {
pub sess: &'tcx Session,
pub span: Span,
pub expr_ty: Ty<'tcx>,
pub cast_ty: String,
}
impl<'tcx> StructuredDiagnostic<'tcx> for SizedUnsizedCast<'tcx> {
fn session(&self) -> &Session {
self.sess
}
|
fn diagnostic_common(&self) -> DiagnosticBuilder<'tcx> {
if self.expr_ty.references_error() {
self.sess.diagnostic().struct_dummy()
} else {
self.sess.struct_span_fatal_with_code(
self.span,
&format!(
"cannot cast thin pointer `{}` to fat pointer `{}`",
self.expr_ty, self.cast_ty
),
self.code(),
)
}
}
fn diagnostic_extended(&self, mut err: DiagnosticBuilder<'tcx>) -> DiagnosticBuilder<'tcx> {
err.help(
"Thin pointers are \"simple\" pointers: they are purely a reference to a
memory address.
Fat pointers are pointers referencing \"Dynamically Sized Types\" (also
called DST). DST don't have a statically known size, therefore they can
only exist behind some kind of pointers that contain additional
information. Slices and trait objects are DSTs. In the case of slices,
the additional information the fat pointer holds is their size.
To fix this error, don't try to cast directly between thin and fat
pointers.
For more information about casts, take a look at The Book:
https://doc.rust-lang.org/reference/expressions/operator-expr.html#type-cast-expressions",
);
err
}
}
|
fn code(&self) -> DiagnosticId {
rustc_errors::error_code!(E0607)
}
|
random_line_split
|
sized_unsized_cast.rs
|
use crate::structured_errors::StructuredDiagnostic;
use rustc_errors::{DiagnosticBuilder, DiagnosticId};
use rustc_middle::ty::{Ty, TypeFoldable};
use rustc_session::Session;
use rustc_span::Span;
pub struct SizedUnsizedCast<'tcx> {
pub sess: &'tcx Session,
pub span: Span,
pub expr_ty: Ty<'tcx>,
pub cast_ty: String,
}
impl<'tcx> StructuredDiagnostic<'tcx> for SizedUnsizedCast<'tcx> {
fn session(&self) -> &Session {
self.sess
}
fn code(&self) -> DiagnosticId
|
fn diagnostic_common(&self) -> DiagnosticBuilder<'tcx> {
if self.expr_ty.references_error() {
self.sess.diagnostic().struct_dummy()
} else {
self.sess.struct_span_fatal_with_code(
self.span,
&format!(
"cannot cast thin pointer `{}` to fat pointer `{}`",
self.expr_ty, self.cast_ty
),
self.code(),
)
}
}
fn diagnostic_extended(&self, mut err: DiagnosticBuilder<'tcx>) -> DiagnosticBuilder<'tcx> {
err.help(
"Thin pointers are \"simple\" pointers: they are purely a reference to a
memory address.
Fat pointers are pointers referencing \"Dynamically Sized Types\" (also
called DST). DST don't have a statically known size, therefore they can
only exist behind some kind of pointers that contain additional
information. Slices and trait objects are DSTs. In the case of slices,
the additional information the fat pointer holds is their size.
To fix this error, don't try to cast directly between thin and fat
pointers.
For more information about casts, take a look at The Book:
https://doc.rust-lang.org/reference/expressions/operator-expr.html#type-cast-expressions",
);
err
}
}
|
{
rustc_errors::error_code!(E0607)
}
|
identifier_body
|
sized_unsized_cast.rs
|
use crate::structured_errors::StructuredDiagnostic;
use rustc_errors::{DiagnosticBuilder, DiagnosticId};
use rustc_middle::ty::{Ty, TypeFoldable};
use rustc_session::Session;
use rustc_span::Span;
pub struct SizedUnsizedCast<'tcx> {
pub sess: &'tcx Session,
pub span: Span,
pub expr_ty: Ty<'tcx>,
pub cast_ty: String,
}
impl<'tcx> StructuredDiagnostic<'tcx> for SizedUnsizedCast<'tcx> {
fn session(&self) -> &Session {
self.sess
}
fn code(&self) -> DiagnosticId {
rustc_errors::error_code!(E0607)
}
fn diagnostic_common(&self) -> DiagnosticBuilder<'tcx> {
if self.expr_ty.references_error() {
self.sess.diagnostic().struct_dummy()
} else
|
}
fn diagnostic_extended(&self, mut err: DiagnosticBuilder<'tcx>) -> DiagnosticBuilder<'tcx> {
err.help(
"Thin pointers are \"simple\" pointers: they are purely a reference to a
memory address.
Fat pointers are pointers referencing \"Dynamically Sized Types\" (also
called DST). DST don't have a statically known size, therefore they can
only exist behind some kind of pointers that contain additional
information. Slices and trait objects are DSTs. In the case of slices,
the additional information the fat pointer holds is their size.
To fix this error, don't try to cast directly between thin and fat
pointers.
For more information about casts, take a look at The Book:
https://doc.rust-lang.org/reference/expressions/operator-expr.html#type-cast-expressions",
);
err
}
}
|
{
self.sess.struct_span_fatal_with_code(
self.span,
&format!(
"cannot cast thin pointer `{}` to fat pointer `{}`",
self.expr_ty, self.cast_ty
),
self.code(),
)
}
|
conditional_block
|
sized_unsized_cast.rs
|
use crate::structured_errors::StructuredDiagnostic;
use rustc_errors::{DiagnosticBuilder, DiagnosticId};
use rustc_middle::ty::{Ty, TypeFoldable};
use rustc_session::Session;
use rustc_span::Span;
pub struct SizedUnsizedCast<'tcx> {
pub sess: &'tcx Session,
pub span: Span,
pub expr_ty: Ty<'tcx>,
pub cast_ty: String,
}
impl<'tcx> StructuredDiagnostic<'tcx> for SizedUnsizedCast<'tcx> {
fn session(&self) -> &Session {
self.sess
}
fn
|
(&self) -> DiagnosticId {
rustc_errors::error_code!(E0607)
}
fn diagnostic_common(&self) -> DiagnosticBuilder<'tcx> {
if self.expr_ty.references_error() {
self.sess.diagnostic().struct_dummy()
} else {
self.sess.struct_span_fatal_with_code(
self.span,
&format!(
"cannot cast thin pointer `{}` to fat pointer `{}`",
self.expr_ty, self.cast_ty
),
self.code(),
)
}
}
fn diagnostic_extended(&self, mut err: DiagnosticBuilder<'tcx>) -> DiagnosticBuilder<'tcx> {
err.help(
"Thin pointers are \"simple\" pointers: they are purely a reference to a
memory address.
Fat pointers are pointers referencing \"Dynamically Sized Types\" (also
called DST). DST don't have a statically known size, therefore they can
only exist behind some kind of pointers that contain additional
information. Slices and trait objects are DSTs. In the case of slices,
the additional information the fat pointer holds is their size.
To fix this error, don't try to cast directly between thin and fat
pointers.
For more information about casts, take a look at The Book:
https://doc.rust-lang.org/reference/expressions/operator-expr.html#type-cast-expressions",
);
err
}
}
|
code
|
identifier_name
|
flock.rs
|
use std::fs::{File, OpenOptions};
use std::io;
use std::io::{Read, Seek, SeekFrom, Write};
use std::path::{Display, Path, PathBuf};
use termcolor::Color::Cyan;
use crate::util::errors::{CargoResult, CargoResultExt};
use crate::util::paths;
use crate::util::Config;
use sys::*;
#[derive(Debug)]
pub struct FileLock {
f: Option<File>,
path: PathBuf,
state: State,
}
#[derive(PartialEq, Debug)]
enum State {
Unlocked,
Shared,
Exclusive,
}
impl FileLock {
/// Returns the underlying file handle of this lock.
pub fn file(&self) -> &File {
self.f.as_ref().unwrap()
}
/// Returns the underlying path that this lock points to.
///
/// Note that special care must be taken to ensure that the path is not
/// referenced outside the lifetime of this lock.
pub fn path(&self) -> &Path {
assert_ne!(self.state, State::Unlocked);
&self.path
}
/// Returns the parent path containing this file
pub fn parent(&self) -> &Path {
assert_ne!(self.state, State::Unlocked);
self.path.parent().unwrap()
}
/// Removes all sibling files to this locked file.
///
/// This can be useful if a directory is locked with a sentinel file but it
/// needs to be cleared out as it may be corrupt.
pub fn remove_siblings(&self) -> CargoResult<()> {
let path = self.path();
for entry in path.parent().unwrap().read_dir()? {
let entry = entry?;
if Some(&entry.file_name()[..]) == path.file_name() {
continue;
}
let kind = entry.file_type()?;
if kind.is_dir() {
paths::remove_dir_all(entry.path())?;
} else {
paths::remove_file(entry.path())?;
}
}
Ok(())
}
}
impl Read for FileLock {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
self.file().read(buf)
}
}
impl Seek for FileLock {
fn seek(&mut self, to: SeekFrom) -> io::Result<u64> {
self.file().seek(to)
}
}
impl Write for FileLock {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.file().write(buf)
}
fn flush(&mut self) -> io::Result<()> {
self.file().flush()
}
}
impl Drop for FileLock {
fn drop(&mut self) {
if self.state!= State::Unlocked {
if let Some(f) = self.f.take() {
let _ = unlock(&f);
}
}
}
}
/// A "filesystem" is intended to be a globally shared, hence locked, resource
/// in Cargo.
///
/// The `Path` of a filesystem cannot be learned unless it's done in a locked
/// fashion, and otherwise functions on this structure are prepared to handle
/// concurrent invocations across multiple instances of Cargo.
#[derive(Clone, Debug)]
pub struct Filesystem {
root: PathBuf,
}
impl Filesystem {
/// Creates a new filesystem to be rooted at the given path.
pub fn new(path: PathBuf) -> Filesystem {
Filesystem { root: path }
}
/// Like `Path::join`, creates a new filesystem rooted at this filesystem
/// joined with the given path.
pub fn join<T: AsRef<Path>>(&self, other: T) -> Filesystem {
Filesystem::new(self.root.join(other))
}
/// Like `Path::push`, pushes a new path component onto this filesystem.
pub fn push<T: AsRef<Path>>(&mut self, other: T) {
self.root.push(other);
}
/// Consumes this filesystem and returns the underlying `PathBuf`.
///
/// Note that this is a relatively dangerous operation and should be used
/// with great caution!.
pub fn into_path_unlocked(self) -> PathBuf {
self.root
}
/// Returns the underlying `Path`.
///
/// Note that this is a relatively dangerous operation and should be used
/// with great caution!.
pub fn as_path_unlocked(&self) -> &Path {
&self.root
}
/// Creates the directory pointed to by this filesystem.
///
/// Handles errors where other Cargo processes are also attempting to
/// concurrently create this directory.
pub fn create_dir(&self) -> CargoResult<()> {
paths::create_dir_all(&self.root)
}
/// Returns an adaptor that can be used to print the path of this
/// filesystem.
pub fn display(&self) -> Display<'_> {
self.root.display()
}
/// Opens exclusive access to a file, returning the locked version of a
/// file.
///
/// This function will create a file at `path` if it doesn't already exist
/// (including intermediate directories), and then it will acquire an
/// exclusive lock on `path`. If the process must block waiting for the
/// lock, the `msg` is printed to `config`.
///
/// The returned file can be accessed to look at the path and also has
/// read/write access to the underlying file.
pub fn open_rw<P>(&self, path: P, config: &Config, msg: &str) -> CargoResult<FileLock>
where
P: AsRef<Path>,
{
self.open(
path.as_ref(),
OpenOptions::new().read(true).write(true).create(true),
State::Exclusive,
config,
msg,
)
}
/// Opens shared access to a file, returning the locked version of a file.
///
/// This function will fail if `path` doesn't already exist, but if it does
/// then it will acquire a shared lock on `path`. If the process must block
/// waiting for the lock, the `msg` is printed to `config`.
///
/// The returned file can be accessed to look at the path and also has read
/// access to the underlying file. Any writes to the file will return an
/// error.
pub fn open_ro<P>(&self, path: P, config: &Config, msg: &str) -> CargoResult<FileLock>
where
P: AsRef<Path>,
{
self.open(
path.as_ref(),
OpenOptions::new().read(true),
State::Shared,
config,
msg,
)
}
fn open(
&self,
path: &Path,
opts: &OpenOptions,
state: State,
config: &Config,
msg: &str,
) -> CargoResult<FileLock> {
let path = self.root.join(path);
// If we want an exclusive lock then if we fail because of NotFound it's
// likely because an intermediate directory didn't exist, so try to
// create the directory and then continue.
let f = opts
.open(&path)
.or_else(|e| {
if e.kind() == io::ErrorKind::NotFound && state == State::Exclusive {
paths::create_dir_all(path.parent().unwrap())?;
Ok(opts.open(&path)?)
} else {
Err(anyhow::Error::from(e))
}
})
.chain_err(|| format!("failed to open: {}", path.display()))?;
match state {
State::Exclusive => {
acquire(config, msg, &path, &|| try_lock_exclusive(&f), &|| {
lock_exclusive(&f)
})?;
}
State::Shared => {
acquire(config, msg, &path, &|| try_lock_shared(&f), &|| {
lock_shared(&f)
})?;
}
State::Unlocked => {}
}
Ok(FileLock {
f: Some(f),
path,
state,
})
}
}
impl PartialEq<Path> for Filesystem {
fn eq(&self, other: &Path) -> bool {
self.root == other
}
}
impl PartialEq<Filesystem> for Path {
fn eq(&self, other: &Filesystem) -> bool {
self == other.root
}
}
/// Acquires a lock on a file in a "nice" manner.
///
/// Almost all long-running blocking actions in Cargo have a status message
/// associated with them as we're not sure how long they'll take. Whenever a
/// conflicted file lock happens, this is the case (we're not sure when the lock
/// will be released).
///
/// This function will acquire the lock on a `path`, printing out a nice message
/// to the console if we have to wait for it. It will first attempt to use `try`
/// to acquire a lock on the crate, and in the case of contention it will emit a
/// status message based on `msg` to `config`'s shell, and then use `block` to
/// block waiting to acquire a lock.
///
/// Returns an error if the lock could not be acquired or if any error other
/// than a contention error happens.
fn acquire(
config: &Config,
msg: &str,
path: &Path,
lock_try: &dyn Fn() -> io::Result<()>,
lock_block: &dyn Fn() -> io::Result<()>,
) -> CargoResult<()> {
// File locking on Unix is currently implemented via `flock`, which is known
// to be broken on NFS. We could in theory just ignore errors that happen on
// NFS, but apparently the failure mode [1] for `flock` on NFS is **blocking
// forever**, even if the "non-blocking" flag is passed!
//
// As a result, we just skip all file locks entirely on NFS mounts. That
// should avoid calling any `flock` functions at all, and it wouldn't work
// there anyway.
//
// [1]: https://github.com/rust-lang/cargo/issues/2615
if is_on_nfs_mount(path) {
return Ok(());
}
match lock_try() {
Ok(()) => return Ok(()),
// In addition to ignoring NFS which is commonly not working we also
// just ignore locking on filesystems that look like they don't
// implement file locking.
Err(e) if error_unsupported(&e) => return Ok(()),
Err(e) => {
if!error_contended(&e) {
let e = anyhow::Error::from(e);
let cx = format!("failed to lock file: {}", path.display());
return Err(e.context(cx));
}
}
}
let msg = format!("waiting for file lock on {}", msg);
config.shell().status_with_color("Blocking", &msg, Cyan)?;
lock_block().chain_err(|| format!("failed to lock file: {}", path.display()))?;
return Ok(());
#[cfg(all(target_os = "linux", not(target_env = "musl")))]
fn is_on_nfs_mount(path: &Path) -> bool {
use std::ffi::CString;
use std::mem;
use std::os::unix::prelude::*;
let path = match CString::new(path.as_os_str().as_bytes()) {
Ok(path) => path,
Err(_) => return false,
};
unsafe {
let mut buf: libc::statfs = mem::zeroed();
let r = libc::statfs(path.as_ptr(), &mut buf);
r == 0 && buf.f_type as u32 == libc::NFS_SUPER_MAGIC as u32
}
}
#[cfg(any(not(target_os = "linux"), target_env = "musl"))]
fn is_on_nfs_mount(_path: &Path) -> bool {
false
}
}
#[cfg(unix)]
mod sys {
use std::fs::File;
use std::io::{Error, Result};
use std::os::unix::io::AsRawFd;
pub(super) fn lock_shared(file: &File) -> Result<()> {
flock(file, libc::LOCK_SH)
}
pub(super) fn lock_exclusive(file: &File) -> Result<()> {
flock(file, libc::LOCK_EX)
}
pub(super) fn try_lock_shared(file: &File) -> Result<()> {
flock(file, libc::LOCK_SH | libc::LOCK_NB)
}
pub(super) fn try_lock_exclusive(file: &File) -> Result<()> {
flock(file, libc::LOCK_EX | libc::LOCK_NB)
}
pub(super) fn unlock(file: &File) -> Result<()> {
flock(file, libc::LOCK_UN)
}
pub(super) fn error_contended(err: &Error) -> bool {
err.raw_os_error().map_or(false, |x| x == libc::EWOULDBLOCK)
}
pub(super) fn error_unsupported(err: &Error) -> bool {
match err.raw_os_error() {
Some(libc::ENOTSUP) => true,
#[cfg(target_os = "linux")]
Some(libc::ENOSYS) => true,
_ => false,
}
}
#[cfg(not(target_os = "solaris"))]
fn flock(file: &File, flag: libc::c_int) -> Result<()> {
let ret = unsafe { libc::flock(file.as_raw_fd(), flag) };
if ret < 0 {
Err(Error::last_os_error())
} else
|
}
#[cfg(target_os = "solaris")]
fn flock(file: &File, flag: libc::c_int) -> Result<()> {
// Solaris lacks flock(), so simply succeed with a no-op
Ok(())
}
}
#[cfg(windows)]
mod sys {
use std::fs::File;
use std::io::{Error, Result};
use std::mem;
use std::os::windows::io::AsRawHandle;
use winapi::shared::minwindef::DWORD;
use winapi::shared::winerror::{ERROR_INVALID_FUNCTION, ERROR_LOCK_VIOLATION};
use winapi::um::fileapi::{LockFileEx, UnlockFile};
use winapi::um::minwinbase::{LOCKFILE_EXCLUSIVE_LOCK, LOCKFILE_FAIL_IMMEDIATELY};
pub(super) fn lock_shared(file: &File) -> Result<()> {
lock_file(file, 0)
}
pub(super) fn lock_exclusive(file: &File) -> Result<()> {
lock_file(file, LOCKFILE_EXCLUSIVE_LOCK)
}
pub(super) fn try_lock_shared(file: &File) -> Result<()> {
lock_file(file, LOCKFILE_FAIL_IMMEDIATELY)
}
pub(super) fn try_lock_exclusive(file: &File) -> Result<()> {
lock_file(file, LOCKFILE_EXCLUSIVE_LOCK | LOCKFILE_FAIL_IMMEDIATELY)
}
pub(super) fn error_contended(err: &Error) -> bool {
err.raw_os_error()
.map_or(false, |x| x == ERROR_LOCK_VIOLATION as i32)
}
pub(super) fn error_unsupported(err: &Error) -> bool {
err.raw_os_error()
.map_or(false, |x| x == ERROR_INVALID_FUNCTION as i32)
}
pub(super) fn unlock(file: &File) -> Result<()> {
unsafe {
let ret = UnlockFile(file.as_raw_handle(), 0, 0,!0,!0);
if ret == 0 {
Err(Error::last_os_error())
} else {
Ok(())
}
}
}
fn lock_file(file: &File, flags: DWORD) -> Result<()> {
unsafe {
let mut overlapped = mem::zeroed();
let ret = LockFileEx(file.as_raw_handle(), flags, 0,!0,!0, &mut overlapped);
if ret == 0 {
Err(Error::last_os_error())
} else {
Ok(())
}
}
}
}
|
{
Ok(())
}
|
conditional_block
|
flock.rs
|
use std::fs::{File, OpenOptions};
use std::io;
use std::io::{Read, Seek, SeekFrom, Write};
use std::path::{Display, Path, PathBuf};
use termcolor::Color::Cyan;
use crate::util::errors::{CargoResult, CargoResultExt};
use crate::util::paths;
use crate::util::Config;
use sys::*;
#[derive(Debug)]
pub struct FileLock {
f: Option<File>,
path: PathBuf,
state: State,
}
#[derive(PartialEq, Debug)]
enum State {
Unlocked,
Shared,
Exclusive,
}
impl FileLock {
/// Returns the underlying file handle of this lock.
pub fn file(&self) -> &File {
self.f.as_ref().unwrap()
}
/// Returns the underlying path that this lock points to.
///
/// Note that special care must be taken to ensure that the path is not
/// referenced outside the lifetime of this lock.
pub fn path(&self) -> &Path {
assert_ne!(self.state, State::Unlocked);
&self.path
}
/// Returns the parent path containing this file
pub fn parent(&self) -> &Path {
assert_ne!(self.state, State::Unlocked);
self.path.parent().unwrap()
}
/// Removes all sibling files to this locked file.
///
/// This can be useful if a directory is locked with a sentinel file but it
/// needs to be cleared out as it may be corrupt.
pub fn remove_siblings(&self) -> CargoResult<()> {
let path = self.path();
for entry in path.parent().unwrap().read_dir()? {
let entry = entry?;
if Some(&entry.file_name()[..]) == path.file_name() {
continue;
}
let kind = entry.file_type()?;
if kind.is_dir() {
paths::remove_dir_all(entry.path())?;
} else {
paths::remove_file(entry.path())?;
}
}
Ok(())
}
}
impl Read for FileLock {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
self.file().read(buf)
}
}
impl Seek for FileLock {
fn seek(&mut self, to: SeekFrom) -> io::Result<u64> {
self.file().seek(to)
}
}
impl Write for FileLock {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.file().write(buf)
}
fn flush(&mut self) -> io::Result<()> {
self.file().flush()
}
}
impl Drop for FileLock {
fn drop(&mut self) {
if self.state!= State::Unlocked {
if let Some(f) = self.f.take() {
let _ = unlock(&f);
}
}
}
}
/// A "filesystem" is intended to be a globally shared, hence locked, resource
/// in Cargo.
///
/// The `Path` of a filesystem cannot be learned unless it's done in a locked
/// fashion, and otherwise functions on this structure are prepared to handle
/// concurrent invocations across multiple instances of Cargo.
#[derive(Clone, Debug)]
pub struct Filesystem {
root: PathBuf,
}
impl Filesystem {
/// Creates a new filesystem to be rooted at the given path.
pub fn new(path: PathBuf) -> Filesystem
|
/// Like `Path::join`, creates a new filesystem rooted at this filesystem
/// joined with the given path.
pub fn join<T: AsRef<Path>>(&self, other: T) -> Filesystem {
Filesystem::new(self.root.join(other))
}
/// Like `Path::push`, pushes a new path component onto this filesystem.
pub fn push<T: AsRef<Path>>(&mut self, other: T) {
self.root.push(other);
}
/// Consumes this filesystem and returns the underlying `PathBuf`.
///
/// Note that this is a relatively dangerous operation and should be used
/// with great caution!.
pub fn into_path_unlocked(self) -> PathBuf {
self.root
}
/// Returns the underlying `Path`.
///
/// Note that this is a relatively dangerous operation and should be used
/// with great caution!.
pub fn as_path_unlocked(&self) -> &Path {
&self.root
}
/// Creates the directory pointed to by this filesystem.
///
/// Handles errors where other Cargo processes are also attempting to
/// concurrently create this directory.
pub fn create_dir(&self) -> CargoResult<()> {
paths::create_dir_all(&self.root)
}
/// Returns an adaptor that can be used to print the path of this
/// filesystem.
pub fn display(&self) -> Display<'_> {
self.root.display()
}
/// Opens exclusive access to a file, returning the locked version of a
/// file.
///
/// This function will create a file at `path` if it doesn't already exist
/// (including intermediate directories), and then it will acquire an
/// exclusive lock on `path`. If the process must block waiting for the
/// lock, the `msg` is printed to `config`.
///
/// The returned file can be accessed to look at the path and also has
/// read/write access to the underlying file.
pub fn open_rw<P>(&self, path: P, config: &Config, msg: &str) -> CargoResult<FileLock>
where
P: AsRef<Path>,
{
self.open(
path.as_ref(),
OpenOptions::new().read(true).write(true).create(true),
State::Exclusive,
config,
msg,
)
}
/// Opens shared access to a file, returning the locked version of a file.
///
/// This function will fail if `path` doesn't already exist, but if it does
/// then it will acquire a shared lock on `path`. If the process must block
/// waiting for the lock, the `msg` is printed to `config`.
///
/// The returned file can be accessed to look at the path and also has read
/// access to the underlying file. Any writes to the file will return an
/// error.
pub fn open_ro<P>(&self, path: P, config: &Config, msg: &str) -> CargoResult<FileLock>
where
P: AsRef<Path>,
{
self.open(
path.as_ref(),
OpenOptions::new().read(true),
State::Shared,
config,
msg,
)
}
fn open(
&self,
path: &Path,
opts: &OpenOptions,
state: State,
config: &Config,
msg: &str,
) -> CargoResult<FileLock> {
let path = self.root.join(path);
// If we want an exclusive lock then if we fail because of NotFound it's
// likely because an intermediate directory didn't exist, so try to
// create the directory and then continue.
let f = opts
.open(&path)
.or_else(|e| {
if e.kind() == io::ErrorKind::NotFound && state == State::Exclusive {
paths::create_dir_all(path.parent().unwrap())?;
Ok(opts.open(&path)?)
} else {
Err(anyhow::Error::from(e))
}
})
.chain_err(|| format!("failed to open: {}", path.display()))?;
match state {
State::Exclusive => {
acquire(config, msg, &path, &|| try_lock_exclusive(&f), &|| {
lock_exclusive(&f)
})?;
}
State::Shared => {
acquire(config, msg, &path, &|| try_lock_shared(&f), &|| {
lock_shared(&f)
})?;
}
State::Unlocked => {}
}
Ok(FileLock {
f: Some(f),
path,
state,
})
}
}
impl PartialEq<Path> for Filesystem {
fn eq(&self, other: &Path) -> bool {
self.root == other
}
}
impl PartialEq<Filesystem> for Path {
fn eq(&self, other: &Filesystem) -> bool {
self == other.root
}
}
/// Acquires a lock on a file in a "nice" manner.
///
/// Almost all long-running blocking actions in Cargo have a status message
/// associated with them as we're not sure how long they'll take. Whenever a
/// conflicted file lock happens, this is the case (we're not sure when the lock
/// will be released).
///
/// This function will acquire the lock on a `path`, printing out a nice message
/// to the console if we have to wait for it. It will first attempt to use `try`
/// to acquire a lock on the crate, and in the case of contention it will emit a
/// status message based on `msg` to `config`'s shell, and then use `block` to
/// block waiting to acquire a lock.
///
/// Returns an error if the lock could not be acquired or if any error other
/// than a contention error happens.
fn acquire(
config: &Config,
msg: &str,
path: &Path,
lock_try: &dyn Fn() -> io::Result<()>,
lock_block: &dyn Fn() -> io::Result<()>,
) -> CargoResult<()> {
// File locking on Unix is currently implemented via `flock`, which is known
// to be broken on NFS. We could in theory just ignore errors that happen on
// NFS, but apparently the failure mode [1] for `flock` on NFS is **blocking
// forever**, even if the "non-blocking" flag is passed!
//
// As a result, we just skip all file locks entirely on NFS mounts. That
// should avoid calling any `flock` functions at all, and it wouldn't work
// there anyway.
//
// [1]: https://github.com/rust-lang/cargo/issues/2615
if is_on_nfs_mount(path) {
return Ok(());
}
match lock_try() {
Ok(()) => return Ok(()),
// In addition to ignoring NFS which is commonly not working we also
// just ignore locking on filesystems that look like they don't
// implement file locking.
Err(e) if error_unsupported(&e) => return Ok(()),
Err(e) => {
if!error_contended(&e) {
let e = anyhow::Error::from(e);
let cx = format!("failed to lock file: {}", path.display());
return Err(e.context(cx));
}
}
}
let msg = format!("waiting for file lock on {}", msg);
config.shell().status_with_color("Blocking", &msg, Cyan)?;
lock_block().chain_err(|| format!("failed to lock file: {}", path.display()))?;
return Ok(());
#[cfg(all(target_os = "linux", not(target_env = "musl")))]
fn is_on_nfs_mount(path: &Path) -> bool {
use std::ffi::CString;
use std::mem;
use std::os::unix::prelude::*;
let path = match CString::new(path.as_os_str().as_bytes()) {
Ok(path) => path,
Err(_) => return false,
};
unsafe {
let mut buf: libc::statfs = mem::zeroed();
let r = libc::statfs(path.as_ptr(), &mut buf);
r == 0 && buf.f_type as u32 == libc::NFS_SUPER_MAGIC as u32
}
}
#[cfg(any(not(target_os = "linux"), target_env = "musl"))]
fn is_on_nfs_mount(_path: &Path) -> bool {
false
}
}
#[cfg(unix)]
mod sys {
use std::fs::File;
use std::io::{Error, Result};
use std::os::unix::io::AsRawFd;
pub(super) fn lock_shared(file: &File) -> Result<()> {
flock(file, libc::LOCK_SH)
}
pub(super) fn lock_exclusive(file: &File) -> Result<()> {
flock(file, libc::LOCK_EX)
}
pub(super) fn try_lock_shared(file: &File) -> Result<()> {
flock(file, libc::LOCK_SH | libc::LOCK_NB)
}
pub(super) fn try_lock_exclusive(file: &File) -> Result<()> {
flock(file, libc::LOCK_EX | libc::LOCK_NB)
}
pub(super) fn unlock(file: &File) -> Result<()> {
flock(file, libc::LOCK_UN)
}
pub(super) fn error_contended(err: &Error) -> bool {
err.raw_os_error().map_or(false, |x| x == libc::EWOULDBLOCK)
}
pub(super) fn error_unsupported(err: &Error) -> bool {
match err.raw_os_error() {
Some(libc::ENOTSUP) => true,
#[cfg(target_os = "linux")]
Some(libc::ENOSYS) => true,
_ => false,
}
}
#[cfg(not(target_os = "solaris"))]
fn flock(file: &File, flag: libc::c_int) -> Result<()> {
let ret = unsafe { libc::flock(file.as_raw_fd(), flag) };
if ret < 0 {
Err(Error::last_os_error())
} else {
Ok(())
}
}
#[cfg(target_os = "solaris")]
fn flock(file: &File, flag: libc::c_int) -> Result<()> {
// Solaris lacks flock(), so simply succeed with a no-op
Ok(())
}
}
#[cfg(windows)]
mod sys {
use std::fs::File;
use std::io::{Error, Result};
use std::mem;
use std::os::windows::io::AsRawHandle;
use winapi::shared::minwindef::DWORD;
use winapi::shared::winerror::{ERROR_INVALID_FUNCTION, ERROR_LOCK_VIOLATION};
use winapi::um::fileapi::{LockFileEx, UnlockFile};
use winapi::um::minwinbase::{LOCKFILE_EXCLUSIVE_LOCK, LOCKFILE_FAIL_IMMEDIATELY};
pub(super) fn lock_shared(file: &File) -> Result<()> {
lock_file(file, 0)
}
pub(super) fn lock_exclusive(file: &File) -> Result<()> {
lock_file(file, LOCKFILE_EXCLUSIVE_LOCK)
}
pub(super) fn try_lock_shared(file: &File) -> Result<()> {
lock_file(file, LOCKFILE_FAIL_IMMEDIATELY)
}
pub(super) fn try_lock_exclusive(file: &File) -> Result<()> {
lock_file(file, LOCKFILE_EXCLUSIVE_LOCK | LOCKFILE_FAIL_IMMEDIATELY)
}
pub(super) fn error_contended(err: &Error) -> bool {
err.raw_os_error()
.map_or(false, |x| x == ERROR_LOCK_VIOLATION as i32)
}
pub(super) fn error_unsupported(err: &Error) -> bool {
err.raw_os_error()
.map_or(false, |x| x == ERROR_INVALID_FUNCTION as i32)
}
pub(super) fn unlock(file: &File) -> Result<()> {
unsafe {
let ret = UnlockFile(file.as_raw_handle(), 0, 0,!0,!0);
if ret == 0 {
Err(Error::last_os_error())
} else {
Ok(())
}
}
}
fn lock_file(file: &File, flags: DWORD) -> Result<()> {
unsafe {
let mut overlapped = mem::zeroed();
let ret = LockFileEx(file.as_raw_handle(), flags, 0,!0,!0, &mut overlapped);
if ret == 0 {
Err(Error::last_os_error())
} else {
Ok(())
}
}
}
}
|
{
Filesystem { root: path }
}
|
identifier_body
|
flock.rs
|
use std::fs::{File, OpenOptions};
use std::io;
use std::io::{Read, Seek, SeekFrom, Write};
use std::path::{Display, Path, PathBuf};
use termcolor::Color::Cyan;
use crate::util::errors::{CargoResult, CargoResultExt};
use crate::util::paths;
use crate::util::Config;
use sys::*;
#[derive(Debug)]
pub struct FileLock {
f: Option<File>,
path: PathBuf,
state: State,
}
#[derive(PartialEq, Debug)]
enum State {
Unlocked,
Shared,
Exclusive,
}
impl FileLock {
/// Returns the underlying file handle of this lock.
pub fn file(&self) -> &File {
self.f.as_ref().unwrap()
}
/// Returns the underlying path that this lock points to.
///
/// Note that special care must be taken to ensure that the path is not
/// referenced outside the lifetime of this lock.
pub fn path(&self) -> &Path {
assert_ne!(self.state, State::Unlocked);
&self.path
}
/// Returns the parent path containing this file
pub fn parent(&self) -> &Path {
assert_ne!(self.state, State::Unlocked);
self.path.parent().unwrap()
}
/// Removes all sibling files to this locked file.
///
/// This can be useful if a directory is locked with a sentinel file but it
/// needs to be cleared out as it may be corrupt.
pub fn remove_siblings(&self) -> CargoResult<()> {
let path = self.path();
for entry in path.parent().unwrap().read_dir()? {
let entry = entry?;
if Some(&entry.file_name()[..]) == path.file_name() {
continue;
}
let kind = entry.file_type()?;
if kind.is_dir() {
paths::remove_dir_all(entry.path())?;
} else {
paths::remove_file(entry.path())?;
}
}
Ok(())
}
}
impl Read for FileLock {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
self.file().read(buf)
}
}
impl Seek for FileLock {
fn seek(&mut self, to: SeekFrom) -> io::Result<u64> {
self.file().seek(to)
}
}
impl Write for FileLock {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.file().write(buf)
}
fn flush(&mut self) -> io::Result<()> {
self.file().flush()
}
}
impl Drop for FileLock {
fn drop(&mut self) {
if self.state!= State::Unlocked {
if let Some(f) = self.f.take() {
let _ = unlock(&f);
}
}
}
}
/// A "filesystem" is intended to be a globally shared, hence locked, resource
/// in Cargo.
///
/// The `Path` of a filesystem cannot be learned unless it's done in a locked
/// fashion, and otherwise functions on this structure are prepared to handle
/// concurrent invocations across multiple instances of Cargo.
#[derive(Clone, Debug)]
pub struct Filesystem {
root: PathBuf,
}
impl Filesystem {
/// Creates a new filesystem to be rooted at the given path.
pub fn new(path: PathBuf) -> Filesystem {
Filesystem { root: path }
}
/// Like `Path::join`, creates a new filesystem rooted at this filesystem
/// joined with the given path.
pub fn join<T: AsRef<Path>>(&self, other: T) -> Filesystem {
Filesystem::new(self.root.join(other))
}
/// Like `Path::push`, pushes a new path component onto this filesystem.
pub fn push<T: AsRef<Path>>(&mut self, other: T) {
self.root.push(other);
}
/// Consumes this filesystem and returns the underlying `PathBuf`.
///
/// Note that this is a relatively dangerous operation and should be used
/// with great caution!.
pub fn into_path_unlocked(self) -> PathBuf {
self.root
}
/// Returns the underlying `Path`.
///
/// Note that this is a relatively dangerous operation and should be used
/// with great caution!.
pub fn as_path_unlocked(&self) -> &Path {
&self.root
}
/// Creates the directory pointed to by this filesystem.
///
/// Handles errors where other Cargo processes are also attempting to
/// concurrently create this directory.
pub fn create_dir(&self) -> CargoResult<()> {
paths::create_dir_all(&self.root)
}
/// Returns an adaptor that can be used to print the path of this
/// filesystem.
pub fn display(&self) -> Display<'_> {
self.root.display()
}
/// Opens exclusive access to a file, returning the locked version of a
/// file.
///
/// This function will create a file at `path` if it doesn't already exist
/// (including intermediate directories), and then it will acquire an
/// exclusive lock on `path`. If the process must block waiting for the
/// lock, the `msg` is printed to `config`.
///
/// The returned file can be accessed to look at the path and also has
/// read/write access to the underlying file.
pub fn open_rw<P>(&self, path: P, config: &Config, msg: &str) -> CargoResult<FileLock>
where
P: AsRef<Path>,
{
self.open(
path.as_ref(),
OpenOptions::new().read(true).write(true).create(true),
State::Exclusive,
config,
msg,
)
}
/// Opens shared access to a file, returning the locked version of a file.
///
/// This function will fail if `path` doesn't already exist, but if it does
/// then it will acquire a shared lock on `path`. If the process must block
/// waiting for the lock, the `msg` is printed to `config`.
///
/// The returned file can be accessed to look at the path and also has read
/// access to the underlying file. Any writes to the file will return an
/// error.
pub fn open_ro<P>(&self, path: P, config: &Config, msg: &str) -> CargoResult<FileLock>
where
P: AsRef<Path>,
{
self.open(
path.as_ref(),
OpenOptions::new().read(true),
State::Shared,
config,
msg,
)
}
fn open(
&self,
path: &Path,
opts: &OpenOptions,
state: State,
config: &Config,
msg: &str,
) -> CargoResult<FileLock> {
let path = self.root.join(path);
// If we want an exclusive lock then if we fail because of NotFound it's
// likely because an intermediate directory didn't exist, so try to
// create the directory and then continue.
let f = opts
.open(&path)
.or_else(|e| {
if e.kind() == io::ErrorKind::NotFound && state == State::Exclusive {
paths::create_dir_all(path.parent().unwrap())?;
Ok(opts.open(&path)?)
} else {
Err(anyhow::Error::from(e))
}
})
.chain_err(|| format!("failed to open: {}", path.display()))?;
match state {
State::Exclusive => {
acquire(config, msg, &path, &|| try_lock_exclusive(&f), &|| {
lock_exclusive(&f)
})?;
}
State::Shared => {
acquire(config, msg, &path, &|| try_lock_shared(&f), &|| {
lock_shared(&f)
})?;
}
State::Unlocked => {}
}
Ok(FileLock {
f: Some(f),
path,
state,
})
}
}
impl PartialEq<Path> for Filesystem {
fn eq(&self, other: &Path) -> bool {
self.root == other
}
}
impl PartialEq<Filesystem> for Path {
fn eq(&self, other: &Filesystem) -> bool {
self == other.root
}
}
/// Acquires a lock on a file in a "nice" manner.
///
/// Almost all long-running blocking actions in Cargo have a status message
/// associated with them as we're not sure how long they'll take. Whenever a
/// conflicted file lock happens, this is the case (we're not sure when the lock
/// will be released).
///
/// This function will acquire the lock on a `path`, printing out a nice message
/// to the console if we have to wait for it. It will first attempt to use `try`
/// to acquire a lock on the crate, and in the case of contention it will emit a
/// status message based on `msg` to `config`'s shell, and then use `block` to
/// block waiting to acquire a lock.
///
/// Returns an error if the lock could not be acquired or if any error other
/// than a contention error happens.
fn acquire(
config: &Config,
msg: &str,
path: &Path,
lock_try: &dyn Fn() -> io::Result<()>,
lock_block: &dyn Fn() -> io::Result<()>,
) -> CargoResult<()> {
// File locking on Unix is currently implemented via `flock`, which is known
// to be broken on NFS. We could in theory just ignore errors that happen on
// NFS, but apparently the failure mode [1] for `flock` on NFS is **blocking
// forever**, even if the "non-blocking" flag is passed!
//
// As a result, we just skip all file locks entirely on NFS mounts. That
// should avoid calling any `flock` functions at all, and it wouldn't work
// there anyway.
//
// [1]: https://github.com/rust-lang/cargo/issues/2615
if is_on_nfs_mount(path) {
return Ok(());
}
match lock_try() {
Ok(()) => return Ok(()),
// In addition to ignoring NFS which is commonly not working we also
// just ignore locking on filesystems that look like they don't
// implement file locking.
Err(e) if error_unsupported(&e) => return Ok(()),
Err(e) => {
if!error_contended(&e) {
let e = anyhow::Error::from(e);
let cx = format!("failed to lock file: {}", path.display());
return Err(e.context(cx));
}
}
}
let msg = format!("waiting for file lock on {}", msg);
config.shell().status_with_color("Blocking", &msg, Cyan)?;
lock_block().chain_err(|| format!("failed to lock file: {}", path.display()))?;
return Ok(());
#[cfg(all(target_os = "linux", not(target_env = "musl")))]
fn is_on_nfs_mount(path: &Path) -> bool {
use std::ffi::CString;
use std::mem;
use std::os::unix::prelude::*;
let path = match CString::new(path.as_os_str().as_bytes()) {
Ok(path) => path,
Err(_) => return false,
};
unsafe {
let mut buf: libc::statfs = mem::zeroed();
let r = libc::statfs(path.as_ptr(), &mut buf);
r == 0 && buf.f_type as u32 == libc::NFS_SUPER_MAGIC as u32
}
}
#[cfg(any(not(target_os = "linux"), target_env = "musl"))]
fn is_on_nfs_mount(_path: &Path) -> bool {
false
}
}
#[cfg(unix)]
mod sys {
use std::fs::File;
use std::io::{Error, Result};
use std::os::unix::io::AsRawFd;
pub(super) fn lock_shared(file: &File) -> Result<()> {
flock(file, libc::LOCK_SH)
}
pub(super) fn lock_exclusive(file: &File) -> Result<()> {
flock(file, libc::LOCK_EX)
}
pub(super) fn try_lock_shared(file: &File) -> Result<()> {
flock(file, libc::LOCK_SH | libc::LOCK_NB)
}
pub(super) fn try_lock_exclusive(file: &File) -> Result<()> {
flock(file, libc::LOCK_EX | libc::LOCK_NB)
}
pub(super) fn unlock(file: &File) -> Result<()> {
flock(file, libc::LOCK_UN)
}
pub(super) fn error_contended(err: &Error) -> bool {
err.raw_os_error().map_or(false, |x| x == libc::EWOULDBLOCK)
}
pub(super) fn error_unsupported(err: &Error) -> bool {
match err.raw_os_error() {
Some(libc::ENOTSUP) => true,
#[cfg(target_os = "linux")]
Some(libc::ENOSYS) => true,
_ => false,
}
}
#[cfg(not(target_os = "solaris"))]
fn flock(file: &File, flag: libc::c_int) -> Result<()> {
let ret = unsafe { libc::flock(file.as_raw_fd(), flag) };
if ret < 0 {
Err(Error::last_os_error())
} else {
Ok(())
}
}
#[cfg(target_os = "solaris")]
fn flock(file: &File, flag: libc::c_int) -> Result<()> {
// Solaris lacks flock(), so simply succeed with a no-op
Ok(())
}
}
#[cfg(windows)]
mod sys {
use std::fs::File;
use std::io::{Error, Result};
use std::mem;
use std::os::windows::io::AsRawHandle;
use winapi::shared::minwindef::DWORD;
use winapi::shared::winerror::{ERROR_INVALID_FUNCTION, ERROR_LOCK_VIOLATION};
use winapi::um::fileapi::{LockFileEx, UnlockFile};
use winapi::um::minwinbase::{LOCKFILE_EXCLUSIVE_LOCK, LOCKFILE_FAIL_IMMEDIATELY};
pub(super) fn lock_shared(file: &File) -> Result<()> {
lock_file(file, 0)
}
pub(super) fn lock_exclusive(file: &File) -> Result<()> {
lock_file(file, LOCKFILE_EXCLUSIVE_LOCK)
}
pub(super) fn try_lock_shared(file: &File) -> Result<()> {
lock_file(file, LOCKFILE_FAIL_IMMEDIATELY)
}
pub(super) fn try_lock_exclusive(file: &File) -> Result<()> {
lock_file(file, LOCKFILE_EXCLUSIVE_LOCK | LOCKFILE_FAIL_IMMEDIATELY)
}
|
pub(super) fn error_unsupported(err: &Error) -> bool {
err.raw_os_error()
.map_or(false, |x| x == ERROR_INVALID_FUNCTION as i32)
}
pub(super) fn unlock(file: &File) -> Result<()> {
unsafe {
let ret = UnlockFile(file.as_raw_handle(), 0, 0,!0,!0);
if ret == 0 {
Err(Error::last_os_error())
} else {
Ok(())
}
}
}
fn lock_file(file: &File, flags: DWORD) -> Result<()> {
unsafe {
let mut overlapped = mem::zeroed();
let ret = LockFileEx(file.as_raw_handle(), flags, 0,!0,!0, &mut overlapped);
if ret == 0 {
Err(Error::last_os_error())
} else {
Ok(())
}
}
}
}
|
pub(super) fn error_contended(err: &Error) -> bool {
err.raw_os_error()
.map_or(false, |x| x == ERROR_LOCK_VIOLATION as i32)
}
|
random_line_split
|
flock.rs
|
use std::fs::{File, OpenOptions};
use std::io;
use std::io::{Read, Seek, SeekFrom, Write};
use std::path::{Display, Path, PathBuf};
use termcolor::Color::Cyan;
use crate::util::errors::{CargoResult, CargoResultExt};
use crate::util::paths;
use crate::util::Config;
use sys::*;
#[derive(Debug)]
pub struct FileLock {
f: Option<File>,
path: PathBuf,
state: State,
}
#[derive(PartialEq, Debug)]
enum State {
Unlocked,
Shared,
Exclusive,
}
impl FileLock {
/// Returns the underlying file handle of this lock.
pub fn file(&self) -> &File {
self.f.as_ref().unwrap()
}
/// Returns the underlying path that this lock points to.
///
/// Note that special care must be taken to ensure that the path is not
/// referenced outside the lifetime of this lock.
pub fn path(&self) -> &Path {
assert_ne!(self.state, State::Unlocked);
&self.path
}
/// Returns the parent path containing this file
pub fn parent(&self) -> &Path {
assert_ne!(self.state, State::Unlocked);
self.path.parent().unwrap()
}
/// Removes all sibling files to this locked file.
///
/// This can be useful if a directory is locked with a sentinel file but it
/// needs to be cleared out as it may be corrupt.
pub fn remove_siblings(&self) -> CargoResult<()> {
let path = self.path();
for entry in path.parent().unwrap().read_dir()? {
let entry = entry?;
if Some(&entry.file_name()[..]) == path.file_name() {
continue;
}
let kind = entry.file_type()?;
if kind.is_dir() {
paths::remove_dir_all(entry.path())?;
} else {
paths::remove_file(entry.path())?;
}
}
Ok(())
}
}
impl Read for FileLock {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
self.file().read(buf)
}
}
impl Seek for FileLock {
fn seek(&mut self, to: SeekFrom) -> io::Result<u64> {
self.file().seek(to)
}
}
impl Write for FileLock {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.file().write(buf)
}
fn flush(&mut self) -> io::Result<()> {
self.file().flush()
}
}
impl Drop for FileLock {
fn drop(&mut self) {
if self.state!= State::Unlocked {
if let Some(f) = self.f.take() {
let _ = unlock(&f);
}
}
}
}
/// A "filesystem" is intended to be a globally shared, hence locked, resource
/// in Cargo.
///
/// The `Path` of a filesystem cannot be learned unless it's done in a locked
/// fashion, and otherwise functions on this structure are prepared to handle
/// concurrent invocations across multiple instances of Cargo.
#[derive(Clone, Debug)]
pub struct Filesystem {
root: PathBuf,
}
impl Filesystem {
/// Creates a new filesystem to be rooted at the given path.
pub fn new(path: PathBuf) -> Filesystem {
Filesystem { root: path }
}
/// Like `Path::join`, creates a new filesystem rooted at this filesystem
/// joined with the given path.
pub fn join<T: AsRef<Path>>(&self, other: T) -> Filesystem {
Filesystem::new(self.root.join(other))
}
/// Like `Path::push`, pushes a new path component onto this filesystem.
pub fn push<T: AsRef<Path>>(&mut self, other: T) {
self.root.push(other);
}
/// Consumes this filesystem and returns the underlying `PathBuf`.
///
/// Note that this is a relatively dangerous operation and should be used
/// with great caution!.
pub fn into_path_unlocked(self) -> PathBuf {
self.root
}
/// Returns the underlying `Path`.
///
/// Note that this is a relatively dangerous operation and should be used
/// with great caution!.
pub fn as_path_unlocked(&self) -> &Path {
&self.root
}
/// Creates the directory pointed to by this filesystem.
///
/// Handles errors where other Cargo processes are also attempting to
/// concurrently create this directory.
pub fn create_dir(&self) -> CargoResult<()> {
paths::create_dir_all(&self.root)
}
/// Returns an adaptor that can be used to print the path of this
/// filesystem.
pub fn display(&self) -> Display<'_> {
self.root.display()
}
/// Opens exclusive access to a file, returning the locked version of a
/// file.
///
/// This function will create a file at `path` if it doesn't already exist
/// (including intermediate directories), and then it will acquire an
/// exclusive lock on `path`. If the process must block waiting for the
/// lock, the `msg` is printed to `config`.
///
/// The returned file can be accessed to look at the path and also has
/// read/write access to the underlying file.
pub fn open_rw<P>(&self, path: P, config: &Config, msg: &str) -> CargoResult<FileLock>
where
P: AsRef<Path>,
{
self.open(
path.as_ref(),
OpenOptions::new().read(true).write(true).create(true),
State::Exclusive,
config,
msg,
)
}
/// Opens shared access to a file, returning the locked version of a file.
///
/// This function will fail if `path` doesn't already exist, but if it does
/// then it will acquire a shared lock on `path`. If the process must block
/// waiting for the lock, the `msg` is printed to `config`.
///
/// The returned file can be accessed to look at the path and also has read
/// access to the underlying file. Any writes to the file will return an
/// error.
pub fn open_ro<P>(&self, path: P, config: &Config, msg: &str) -> CargoResult<FileLock>
where
P: AsRef<Path>,
{
self.open(
path.as_ref(),
OpenOptions::new().read(true),
State::Shared,
config,
msg,
)
}
fn open(
&self,
path: &Path,
opts: &OpenOptions,
state: State,
config: &Config,
msg: &str,
) -> CargoResult<FileLock> {
let path = self.root.join(path);
// If we want an exclusive lock then if we fail because of NotFound it's
// likely because an intermediate directory didn't exist, so try to
// create the directory and then continue.
let f = opts
.open(&path)
.or_else(|e| {
if e.kind() == io::ErrorKind::NotFound && state == State::Exclusive {
paths::create_dir_all(path.parent().unwrap())?;
Ok(opts.open(&path)?)
} else {
Err(anyhow::Error::from(e))
}
})
.chain_err(|| format!("failed to open: {}", path.display()))?;
match state {
State::Exclusive => {
acquire(config, msg, &path, &|| try_lock_exclusive(&f), &|| {
lock_exclusive(&f)
})?;
}
State::Shared => {
acquire(config, msg, &path, &|| try_lock_shared(&f), &|| {
lock_shared(&f)
})?;
}
State::Unlocked => {}
}
Ok(FileLock {
f: Some(f),
path,
state,
})
}
}
impl PartialEq<Path> for Filesystem {
fn eq(&self, other: &Path) -> bool {
self.root == other
}
}
impl PartialEq<Filesystem> for Path {
fn eq(&self, other: &Filesystem) -> bool {
self == other.root
}
}
/// Acquires a lock on a file in a "nice" manner.
///
/// Almost all long-running blocking actions in Cargo have a status message
/// associated with them as we're not sure how long they'll take. Whenever a
/// conflicted file lock happens, this is the case (we're not sure when the lock
/// will be released).
///
/// This function will acquire the lock on a `path`, printing out a nice message
/// to the console if we have to wait for it. It will first attempt to use `try`
/// to acquire a lock on the crate, and in the case of contention it will emit a
/// status message based on `msg` to `config`'s shell, and then use `block` to
/// block waiting to acquire a lock.
///
/// Returns an error if the lock could not be acquired or if any error other
/// than a contention error happens.
fn acquire(
config: &Config,
msg: &str,
path: &Path,
lock_try: &dyn Fn() -> io::Result<()>,
lock_block: &dyn Fn() -> io::Result<()>,
) -> CargoResult<()> {
// File locking on Unix is currently implemented via `flock`, which is known
// to be broken on NFS. We could in theory just ignore errors that happen on
// NFS, but apparently the failure mode [1] for `flock` on NFS is **blocking
// forever**, even if the "non-blocking" flag is passed!
//
// As a result, we just skip all file locks entirely on NFS mounts. That
// should avoid calling any `flock` functions at all, and it wouldn't work
// there anyway.
//
// [1]: https://github.com/rust-lang/cargo/issues/2615
if is_on_nfs_mount(path) {
return Ok(());
}
match lock_try() {
Ok(()) => return Ok(()),
// In addition to ignoring NFS which is commonly not working we also
// just ignore locking on filesystems that look like they don't
// implement file locking.
Err(e) if error_unsupported(&e) => return Ok(()),
Err(e) => {
if!error_contended(&e) {
let e = anyhow::Error::from(e);
let cx = format!("failed to lock file: {}", path.display());
return Err(e.context(cx));
}
}
}
let msg = format!("waiting for file lock on {}", msg);
config.shell().status_with_color("Blocking", &msg, Cyan)?;
lock_block().chain_err(|| format!("failed to lock file: {}", path.display()))?;
return Ok(());
#[cfg(all(target_os = "linux", not(target_env = "musl")))]
fn is_on_nfs_mount(path: &Path) -> bool {
use std::ffi::CString;
use std::mem;
use std::os::unix::prelude::*;
let path = match CString::new(path.as_os_str().as_bytes()) {
Ok(path) => path,
Err(_) => return false,
};
unsafe {
let mut buf: libc::statfs = mem::zeroed();
let r = libc::statfs(path.as_ptr(), &mut buf);
r == 0 && buf.f_type as u32 == libc::NFS_SUPER_MAGIC as u32
}
}
#[cfg(any(not(target_os = "linux"), target_env = "musl"))]
fn is_on_nfs_mount(_path: &Path) -> bool {
false
}
}
#[cfg(unix)]
mod sys {
use std::fs::File;
use std::io::{Error, Result};
use std::os::unix::io::AsRawFd;
pub(super) fn lock_shared(file: &File) -> Result<()> {
flock(file, libc::LOCK_SH)
}
pub(super) fn lock_exclusive(file: &File) -> Result<()> {
flock(file, libc::LOCK_EX)
}
pub(super) fn try_lock_shared(file: &File) -> Result<()> {
flock(file, libc::LOCK_SH | libc::LOCK_NB)
}
pub(super) fn try_lock_exclusive(file: &File) -> Result<()> {
flock(file, libc::LOCK_EX | libc::LOCK_NB)
}
pub(super) fn unlock(file: &File) -> Result<()> {
flock(file, libc::LOCK_UN)
}
pub(super) fn error_contended(err: &Error) -> bool {
err.raw_os_error().map_or(false, |x| x == libc::EWOULDBLOCK)
}
pub(super) fn error_unsupported(err: &Error) -> bool {
match err.raw_os_error() {
Some(libc::ENOTSUP) => true,
#[cfg(target_os = "linux")]
Some(libc::ENOSYS) => true,
_ => false,
}
}
#[cfg(not(target_os = "solaris"))]
fn flock(file: &File, flag: libc::c_int) -> Result<()> {
let ret = unsafe { libc::flock(file.as_raw_fd(), flag) };
if ret < 0 {
Err(Error::last_os_error())
} else {
Ok(())
}
}
#[cfg(target_os = "solaris")]
fn
|
(file: &File, flag: libc::c_int) -> Result<()> {
// Solaris lacks flock(), so simply succeed with a no-op
Ok(())
}
}
#[cfg(windows)]
mod sys {
use std::fs::File;
use std::io::{Error, Result};
use std::mem;
use std::os::windows::io::AsRawHandle;
use winapi::shared::minwindef::DWORD;
use winapi::shared::winerror::{ERROR_INVALID_FUNCTION, ERROR_LOCK_VIOLATION};
use winapi::um::fileapi::{LockFileEx, UnlockFile};
use winapi::um::minwinbase::{LOCKFILE_EXCLUSIVE_LOCK, LOCKFILE_FAIL_IMMEDIATELY};
pub(super) fn lock_shared(file: &File) -> Result<()> {
lock_file(file, 0)
}
pub(super) fn lock_exclusive(file: &File) -> Result<()> {
lock_file(file, LOCKFILE_EXCLUSIVE_LOCK)
}
pub(super) fn try_lock_shared(file: &File) -> Result<()> {
lock_file(file, LOCKFILE_FAIL_IMMEDIATELY)
}
pub(super) fn try_lock_exclusive(file: &File) -> Result<()> {
lock_file(file, LOCKFILE_EXCLUSIVE_LOCK | LOCKFILE_FAIL_IMMEDIATELY)
}
pub(super) fn error_contended(err: &Error) -> bool {
err.raw_os_error()
.map_or(false, |x| x == ERROR_LOCK_VIOLATION as i32)
}
pub(super) fn error_unsupported(err: &Error) -> bool {
err.raw_os_error()
.map_or(false, |x| x == ERROR_INVALID_FUNCTION as i32)
}
pub(super) fn unlock(file: &File) -> Result<()> {
unsafe {
let ret = UnlockFile(file.as_raw_handle(), 0, 0,!0,!0);
if ret == 0 {
Err(Error::last_os_error())
} else {
Ok(())
}
}
}
fn lock_file(file: &File, flags: DWORD) -> Result<()> {
unsafe {
let mut overlapped = mem::zeroed();
let ret = LockFileEx(file.as_raw_handle(), flags, 0,!0,!0, &mut overlapped);
if ret == 0 {
Err(Error::last_os_error())
} else {
Ok(())
}
}
}
}
|
flock
|
identifier_name
|
chmod.rs
|
#![crate_name = "uu_chmod"]
/*
* This file is part of the uutils coreutils package.
*
* (c) Arcterus <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
extern crate getopts;
extern crate libc;
extern crate walker;
#[macro_use]
extern crate uucore;
use getopts::Options;
use std::error::Error;
use std::ffi::CString;
use std::io::{self, Write};
use std::mem;
use std::path::Path;
use walker::Walker;
const NAME: &'static str = "chmod";
const VERSION: &'static str = env!("CARGO_PKG_VERSION");
pub fn uumain(mut args: Vec<String>) -> i32 {
let mut opts = Options::new();
opts.optflag("c", "changes", "like verbose but report only when a change is made (unimplemented)");
opts.optflag("f", "quiet", "suppress most error messages (unimplemented)"); // TODO: support --silent
opts.optflag("v", "verbose", "output a diagnostic for every file processed (unimplemented)");
opts.optflag("", "no-preserve-root", "do not treat '/' specially (the default)");
opts.optflag("", "preserve-root", "fail to operate recursively on '/'");
opts.optopt("", "reference", "use RFILE's mode instead of MODE values", "RFILE");
opts.optflag("R", "recursive", "change files and directories recursively");
opts.optflag("h", "help", "display this help and exit");
opts.optflag("V", "version", "output version information and exit");
// sanitize input for - at beginning (e.g. chmod -x testfile). Remove
// the option and save it for later, after parsing is finished.
let mut negative_option = None;
for i in 0..args.len() {
if let Some(first) = args[i].chars().nth(0) {
if first!= '-' {
continue;
}
if let Some(second) = args[i].chars().nth(1) {
match second {
'r' | 'w' | 'x' | 'X' |'s' | 't' | 'u' | 'g' | 'o' | '0'... '7' => {
negative_option = Some(args.remove(i));
break;
},
_ => {}
}
}
}
}
let mut matches = match opts.parse(&args[1..]) {
Ok(m) => m,
Err(f) => { crash!(1, "{}", f) }
};
if matches.opt_present("help") {
let msg = format!("{name} {version}
Usage:
{program} [OPTION]... MODE[,MODE]... FILE...
{program} [OPTION]... OCTAL-MODE FILE...
{program} [OPTION]... --reference=RFILE FILE...
Change the mode of each FILE to MODE.
With --reference, change the mode of each FILE to that of RFILE.
Each MODE is of the form '[ugoa]*([-+=]([rwxXst]*|[ugo]))+|[-+=]?[0-7]+'.",
name = NAME, version = VERSION, program = NAME);
print!("{}", opts.usage(&msg));
return 0;
} else if matches.opt_present("version") {
println!("{} {}", NAME, VERSION);
} else if matches.free.is_empty() {
show_error!("missing an argument");
show_error!("for help, try '{} --help'", NAME);
return 1;
} else {
let changes = matches.opt_present("changes");
let quiet = matches.opt_present("quiet");
let verbose = matches.opt_present("verbose");
let preserve_root = matches.opt_present("preserve-root");
let recursive = matches.opt_present("recursive");
let fmode = matches.opt_str("reference").and_then(|fref| {
let s = CString::new(fref).unwrap_or_else( |_| {
crash!(1, "reference file name contains internal nul byte")
});
let mut stat : libc::stat = unsafe { mem::uninitialized() };
let statres = unsafe { libc::stat(s.as_ptr() as *const _, &mut stat as *mut libc::stat) };
if statres == 0 {
Some(stat.st_mode)
} else {
crash!(1, "cannot stat attribues of '{}': {}", matches.opt_str("reference").unwrap(), io::Error::last_os_error())
}
});
let cmode =
if fmode.is_none() {
// If there was a negative option, now it's a good time to
// use it.
if negative_option.is_some() {
negative_option
} else {
Some(matches.free.remove(0))
}
} else {
None
};
match chmod(matches.free, changes, quiet, verbose, preserve_root,
recursive, fmode, cmode.as_ref()) {
Ok(()) => {}
Err(e) => return e
}
}
0
}
fn chmod(files: Vec<String>, changes: bool, quiet: bool, verbose: bool, preserve_root: bool, recursive: bool, fmode: Option<libc::mode_t>, cmode: Option<&String>) -> Result<(), i32> {
let mut r = Ok(());
for filename in &files {
let filename = &filename[..];
let file = Path::new(filename);
if file.exists() {
if file.is_dir() {
if!preserve_root || filename!= "/" {
if recursive {
let walk_dir = match Walker::new(&file) {
Ok(m) => m,
Err(f) => {
crash!(1, "{}", f.to_string());
}
};
// XXX: here (and elsewhere) we see that this impl will have issues
// with non-UTF-8 filenames. Using OsString won't fix this because
// on Windows OsStrings cannot be built out of non-UTF-8 chars. One
// possible fix is to use CStrings rather than Strings in the args
// to chmod() and chmod_file().
r = chmod(walk_dir.filter_map(|x| match x {
Ok(o) => match o.path().into_os_string().to_str() {
Some(s) => Some(s.to_owned()),
None => None,
},
Err(_) => None,
}).collect(),
changes, quiet, verbose, preserve_root, recursive, fmode, cmode).and(r);
r = chmod_file(&file, filename, changes, quiet, verbose, fmode, cmode).and(r);
}
} else {
show_error!("could not change permissions of directory '{}'",
filename);
r = Err(1);
}
} else {
r = chmod_file(&file, filename, changes, quiet, verbose, fmode, cmode).and(r);
}
} else {
show_error!("no such file or directory '{}'", filename);
r = Err(1);
}
}
r
}
#[cfg(windows)]
fn
|
(file: &Path, name: &str, changes: bool, quiet: bool, verbose: bool, fmode: Option<libc::mode_t>, cmode: Option<&String>) -> Result<(), i32> {
// chmod is useless on Windows
// it doesn't set any permissions at all
// instead it just sets the readonly attribute on the file
Err(0)
}
#[cfg(unix)]
fn chmod_file(file: &Path, name: &str, changes: bool, quiet: bool, verbose: bool, fmode: Option<libc::mode_t>, cmode: Option<&String>) -> Result<(), i32> {
let path = CString::new(name).unwrap_or_else(|e| panic!("{}", e));
let mut stat: libc::stat = unsafe { mem::uninitialized() };
let statres = unsafe { libc::stat(path.as_ptr(), &mut stat as *mut libc::stat) };
let mut fperm =
if statres == 0 {
stat.st_mode & 0o7777
} else {
if!quiet {
show_error!("{}", io::Error::last_os_error());
}
return Err(1);
};
match fmode {
Some(mode) => try!(change_file(fperm, mode, file, &path, verbose, changes, quiet)),
None => {
for mode in cmode.unwrap().split(',') { // cmode is guaranteed to be Some in this case
let arr: &[char] = &['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
let result =
if mode.contains(arr) {
parse_numeric(fperm, mode)
} else {
parse_symbolic(fperm, mode, file)
};
match result {
Ok(mode) => {
try!(change_file(fperm, mode, file, &path, verbose, changes, quiet));
fperm = mode;
}
Err(f) => {
if!quiet {
show_error!("{}", f);
}
return Err(1);
}
}
}
}
}
Ok(())
}
fn parse_numeric(fperm: libc::mode_t, mut mode: &str) -> Result<libc::mode_t, String> {
let (op, pos) = try!(parse_op(mode, Some('=')));
mode = mode[pos..].trim_left_matches('0');
if mode.len() > 4 {
Err(format!("mode is too large ({} > 7777)", mode))
} else {
match libc::mode_t::from_str_radix(mode, 8) {
Ok(change) => {
Ok(match op {
'+' => fperm | change,
'-' => fperm &!change,
'=' => change,
_ => unreachable!()
})
}
Err(err) => Err(err.description().to_owned())
}
}
}
fn parse_symbolic(mut fperm: libc::mode_t, mut mode: &str, file: &Path) -> Result<libc::mode_t, String> {
let (mask, pos) = parse_levels(mode);
if pos == mode.len() {
return Err(format!("invalid mode ({})", mode));
}
mode = &mode[pos..];
while mode.len() > 0 {
let (op, pos) = try!(parse_op(mode, None));
mode = &mode[pos..];
let (srwx, pos) = parse_change(mode, fperm, file);
mode = &mode[pos..];
match op {
'+' => fperm |= srwx & mask,
'-' => fperm &=!(srwx & mask),
'=' => fperm = (fperm &!mask) | (srwx & mask),
_ => unreachable!()
}
}
Ok(fperm)
}
fn parse_levels(mode: &str) -> (libc::mode_t, usize) {
let mut mask = 0;
let mut pos = 0;
for ch in mode.chars() {
mask |= match ch {
'u' => 0o7700,
'g' => 0o7070,
'o' => 0o7007,
'a' => 0o7777,
_ => break
};
pos += 1;
}
if pos == 0 {
mask = 0o7777; // default to 'a'
}
(mask, pos)
}
fn parse_op(mode: &str, default: Option<char>) -> Result<(char, usize), String> {
match mode.chars().next() {
Some(ch) => match ch {
'+' | '-' | '=' => Ok((ch, 1)),
_ => match default {
Some(ch) => Ok((ch, 0)),
None => Err(format!("invalid operator (expected +, -, or =, but found {})", ch))
}
},
None => Err("unexpected end of mode".to_owned())
}
}
fn parse_change(mode: &str, fperm: libc::mode_t, file: &Path) -> (libc::mode_t, usize) {
let mut srwx = fperm & 0o7000;
let mut pos = 0;
for ch in mode.chars() {
match ch {
'r' => srwx |= 0o444,
'w' => srwx |= 0o222,
'x' => srwx |= 0o111,
'X' => {
if file.is_dir() || (fperm & 0o0111)!= 0 {
srwx |= 0o111
}
}
's' => srwx |= 0o4000 | 0o2000,
't' => srwx |= 0o1000,
'u' => srwx = (fperm & 0o700) | ((fperm >> 3) & 0o070) | ((fperm >> 6) & 0o007),
'g' => srwx = ((fperm << 3) & 0o700) | (fperm & 0o070) | ((fperm >> 3) & 0o007),
'o' => srwx = ((fperm << 6) & 0o700) | ((fperm << 3) & 0o070) | (fperm & 0o007),
_ => break
};
pos += 1;
}
if pos == 0 {
srwx = 0;
}
(srwx, pos)
}
fn change_file(fperm: libc::mode_t, mode: libc::mode_t, file: &Path, path: &CString, verbose: bool, changes: bool, quiet: bool) -> Result<(), i32> {
if fperm == mode {
if verbose &&!changes {
show_info!("mode of '{}' retained as {:o}", file.display(), fperm);
}
Ok(())
} else if unsafe { libc::chmod(path.as_ptr(), mode) } == 0 {
if verbose || changes {
show_info!("mode of '{}' changed from {:o} to {:o}", file.display(), fperm, mode);
}
Ok(())
} else {
if!quiet {
show_error!("{}", io::Error::last_os_error());
}
if verbose {
show_info!("failed to change mode of file '{}' from {:o} to {:o}", file.display(), fperm, mode);
}
return Err(1);
}
}
|
chmod_file
|
identifier_name
|
chmod.rs
|
#![crate_name = "uu_chmod"]
/*
* This file is part of the uutils coreutils package.
*
* (c) Arcterus <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
extern crate getopts;
extern crate libc;
extern crate walker;
#[macro_use]
extern crate uucore;
use getopts::Options;
use std::error::Error;
use std::ffi::CString;
use std::io::{self, Write};
use std::mem;
use std::path::Path;
use walker::Walker;
const NAME: &'static str = "chmod";
const VERSION: &'static str = env!("CARGO_PKG_VERSION");
pub fn uumain(mut args: Vec<String>) -> i32 {
let mut opts = Options::new();
opts.optflag("c", "changes", "like verbose but report only when a change is made (unimplemented)");
opts.optflag("f", "quiet", "suppress most error messages (unimplemented)"); // TODO: support --silent
opts.optflag("v", "verbose", "output a diagnostic for every file processed (unimplemented)");
opts.optflag("", "no-preserve-root", "do not treat '/' specially (the default)");
opts.optflag("", "preserve-root", "fail to operate recursively on '/'");
opts.optopt("", "reference", "use RFILE's mode instead of MODE values", "RFILE");
opts.optflag("R", "recursive", "change files and directories recursively");
opts.optflag("h", "help", "display this help and exit");
opts.optflag("V", "version", "output version information and exit");
// sanitize input for - at beginning (e.g. chmod -x testfile). Remove
// the option and save it for later, after parsing is finished.
let mut negative_option = None;
for i in 0..args.len() {
if let Some(first) = args[i].chars().nth(0) {
if first!= '-' {
continue;
}
if let Some(second) = args[i].chars().nth(1) {
match second {
'r' | 'w' | 'x' | 'X' |'s' | 't' | 'u' | 'g' | 'o' | '0'... '7' => {
negative_option = Some(args.remove(i));
break;
},
_ => {}
}
}
}
}
let mut matches = match opts.parse(&args[1..]) {
Ok(m) => m,
Err(f) => { crash!(1, "{}", f) }
};
if matches.opt_present("help") {
let msg = format!("{name} {version}
Usage:
{program} [OPTION]... MODE[,MODE]... FILE...
{program} [OPTION]... OCTAL-MODE FILE...
{program} [OPTION]... --reference=RFILE FILE...
Change the mode of each FILE to MODE.
With --reference, change the mode of each FILE to that of RFILE.
Each MODE is of the form '[ugoa]*([-+=]([rwxXst]*|[ugo]))+|[-+=]?[0-7]+'.",
name = NAME, version = VERSION, program = NAME);
print!("{}", opts.usage(&msg));
return 0;
} else if matches.opt_present("version") {
println!("{} {}", NAME, VERSION);
} else if matches.free.is_empty() {
show_error!("missing an argument");
show_error!("for help, try '{} --help'", NAME);
return 1;
} else {
let changes = matches.opt_present("changes");
let quiet = matches.opt_present("quiet");
let verbose = matches.opt_present("verbose");
let preserve_root = matches.opt_present("preserve-root");
let recursive = matches.opt_present("recursive");
let fmode = matches.opt_str("reference").and_then(|fref| {
let s = CString::new(fref).unwrap_or_else( |_| {
crash!(1, "reference file name contains internal nul byte")
});
let mut stat : libc::stat = unsafe { mem::uninitialized() };
let statres = unsafe { libc::stat(s.as_ptr() as *const _, &mut stat as *mut libc::stat) };
if statres == 0 {
Some(stat.st_mode)
} else {
crash!(1, "cannot stat attribues of '{}': {}", matches.opt_str("reference").unwrap(), io::Error::last_os_error())
}
});
let cmode =
if fmode.is_none() {
// If there was a negative option, now it's a good time to
// use it.
if negative_option.is_some() {
negative_option
} else {
Some(matches.free.remove(0))
}
} else {
None
};
match chmod(matches.free, changes, quiet, verbose, preserve_root,
recursive, fmode, cmode.as_ref()) {
Ok(()) => {}
Err(e) => return e
}
}
0
}
fn chmod(files: Vec<String>, changes: bool, quiet: bool, verbose: bool, preserve_root: bool, recursive: bool, fmode: Option<libc::mode_t>, cmode: Option<&String>) -> Result<(), i32> {
let mut r = Ok(());
for filename in &files {
let filename = &filename[..];
let file = Path::new(filename);
if file.exists() {
if file.is_dir() {
if!preserve_root || filename!= "/" {
if recursive {
let walk_dir = match Walker::new(&file) {
Ok(m) => m,
Err(f) => {
crash!(1, "{}", f.to_string());
}
};
// XXX: here (and elsewhere) we see that this impl will have issues
// with non-UTF-8 filenames. Using OsString won't fix this because
// on Windows OsStrings cannot be built out of non-UTF-8 chars. One
// possible fix is to use CStrings rather than Strings in the args
// to chmod() and chmod_file().
r = chmod(walk_dir.filter_map(|x| match x {
Ok(o) => match o.path().into_os_string().to_str() {
Some(s) => Some(s.to_owned()),
None => None,
},
Err(_) => None,
}).collect(),
changes, quiet, verbose, preserve_root, recursive, fmode, cmode).and(r);
r = chmod_file(&file, filename, changes, quiet, verbose, fmode, cmode).and(r);
}
} else {
show_error!("could not change permissions of directory '{}'",
filename);
r = Err(1);
}
} else {
r = chmod_file(&file, filename, changes, quiet, verbose, fmode, cmode).and(r);
}
} else {
show_error!("no such file or directory '{}'", filename);
r = Err(1);
}
}
r
}
#[cfg(windows)]
fn chmod_file(file: &Path, name: &str, changes: bool, quiet: bool, verbose: bool, fmode: Option<libc::mode_t>, cmode: Option<&String>) -> Result<(), i32> {
// chmod is useless on Windows
// it doesn't set any permissions at all
// instead it just sets the readonly attribute on the file
Err(0)
}
#[cfg(unix)]
fn chmod_file(file: &Path, name: &str, changes: bool, quiet: bool, verbose: bool, fmode: Option<libc::mode_t>, cmode: Option<&String>) -> Result<(), i32> {
let path = CString::new(name).unwrap_or_else(|e| panic!("{}", e));
let mut stat: libc::stat = unsafe { mem::uninitialized() };
let statres = unsafe { libc::stat(path.as_ptr(), &mut stat as *mut libc::stat) };
let mut fperm =
if statres == 0 {
stat.st_mode & 0o7777
} else {
if!quiet {
show_error!("{}", io::Error::last_os_error());
}
return Err(1);
};
match fmode {
Some(mode) => try!(change_file(fperm, mode, file, &path, verbose, changes, quiet)),
None => {
for mode in cmode.unwrap().split(',') { // cmode is guaranteed to be Some in this case
let arr: &[char] = &['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
let result =
if mode.contains(arr) {
parse_numeric(fperm, mode)
} else {
parse_symbolic(fperm, mode, file)
};
match result {
Ok(mode) => {
try!(change_file(fperm, mode, file, &path, verbose, changes, quiet));
fperm = mode;
}
Err(f) => {
if!quiet {
show_error!("{}", f);
}
return Err(1);
}
}
}
}
}
Ok(())
}
fn parse_numeric(fperm: libc::mode_t, mut mode: &str) -> Result<libc::mode_t, String> {
let (op, pos) = try!(parse_op(mode, Some('=')));
mode = mode[pos..].trim_left_matches('0');
if mode.len() > 4 {
Err(format!("mode is too large ({} > 7777)", mode))
} else {
match libc::mode_t::from_str_radix(mode, 8) {
Ok(change) => {
Ok(match op {
'+' => fperm | change,
'-' => fperm &!change,
'=' => change,
_ => unreachable!()
})
}
Err(err) => Err(err.description().to_owned())
}
}
}
fn parse_symbolic(mut fperm: libc::mode_t, mut mode: &str, file: &Path) -> Result<libc::mode_t, String> {
let (mask, pos) = parse_levels(mode);
if pos == mode.len()
|
mode = &mode[pos..];
while mode.len() > 0 {
let (op, pos) = try!(parse_op(mode, None));
mode = &mode[pos..];
let (srwx, pos) = parse_change(mode, fperm, file);
mode = &mode[pos..];
match op {
'+' => fperm |= srwx & mask,
'-' => fperm &=!(srwx & mask),
'=' => fperm = (fperm &!mask) | (srwx & mask),
_ => unreachable!()
}
}
Ok(fperm)
}
fn parse_levels(mode: &str) -> (libc::mode_t, usize) {
let mut mask = 0;
let mut pos = 0;
for ch in mode.chars() {
mask |= match ch {
'u' => 0o7700,
'g' => 0o7070,
'o' => 0o7007,
'a' => 0o7777,
_ => break
};
pos += 1;
}
if pos == 0 {
mask = 0o7777; // default to 'a'
}
(mask, pos)
}
fn parse_op(mode: &str, default: Option<char>) -> Result<(char, usize), String> {
match mode.chars().next() {
Some(ch) => match ch {
'+' | '-' | '=' => Ok((ch, 1)),
_ => match default {
Some(ch) => Ok((ch, 0)),
None => Err(format!("invalid operator (expected +, -, or =, but found {})", ch))
}
},
None => Err("unexpected end of mode".to_owned())
}
}
fn parse_change(mode: &str, fperm: libc::mode_t, file: &Path) -> (libc::mode_t, usize) {
let mut srwx = fperm & 0o7000;
let mut pos = 0;
for ch in mode.chars() {
match ch {
'r' => srwx |= 0o444,
'w' => srwx |= 0o222,
'x' => srwx |= 0o111,
'X' => {
if file.is_dir() || (fperm & 0o0111)!= 0 {
srwx |= 0o111
}
}
's' => srwx |= 0o4000 | 0o2000,
't' => srwx |= 0o1000,
'u' => srwx = (fperm & 0o700) | ((fperm >> 3) & 0o070) | ((fperm >> 6) & 0o007),
'g' => srwx = ((fperm << 3) & 0o700) | (fperm & 0o070) | ((fperm >> 3) & 0o007),
'o' => srwx = ((fperm << 6) & 0o700) | ((fperm << 3) & 0o070) | (fperm & 0o007),
_ => break
};
pos += 1;
}
if pos == 0 {
srwx = 0;
}
(srwx, pos)
}
fn change_file(fperm: libc::mode_t, mode: libc::mode_t, file: &Path, path: &CString, verbose: bool, changes: bool, quiet: bool) -> Result<(), i32> {
if fperm == mode {
if verbose &&!changes {
show_info!("mode of '{}' retained as {:o}", file.display(), fperm);
}
Ok(())
} else if unsafe { libc::chmod(path.as_ptr(), mode) } == 0 {
if verbose || changes {
show_info!("mode of '{}' changed from {:o} to {:o}", file.display(), fperm, mode);
}
Ok(())
} else {
if!quiet {
show_error!("{}", io::Error::last_os_error());
}
if verbose {
show_info!("failed to change mode of file '{}' from {:o} to {:o}", file.display(), fperm, mode);
}
return Err(1);
}
}
|
{
return Err(format!("invalid mode ({})", mode));
}
|
conditional_block
|
chmod.rs
|
#![crate_name = "uu_chmod"]
/*
* This file is part of the uutils coreutils package.
*
* (c) Arcterus <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
extern crate getopts;
extern crate libc;
extern crate walker;
#[macro_use]
extern crate uucore;
use getopts::Options;
use std::error::Error;
use std::ffi::CString;
use std::io::{self, Write};
use std::mem;
use std::path::Path;
use walker::Walker;
const NAME: &'static str = "chmod";
const VERSION: &'static str = env!("CARGO_PKG_VERSION");
pub fn uumain(mut args: Vec<String>) -> i32 {
let mut opts = Options::new();
opts.optflag("c", "changes", "like verbose but report only when a change is made (unimplemented)");
opts.optflag("f", "quiet", "suppress most error messages (unimplemented)"); // TODO: support --silent
opts.optflag("v", "verbose", "output a diagnostic for every file processed (unimplemented)");
opts.optflag("", "no-preserve-root", "do not treat '/' specially (the default)");
opts.optflag("", "preserve-root", "fail to operate recursively on '/'");
opts.optopt("", "reference", "use RFILE's mode instead of MODE values", "RFILE");
opts.optflag("R", "recursive", "change files and directories recursively");
opts.optflag("h", "help", "display this help and exit");
opts.optflag("V", "version", "output version information and exit");
// sanitize input for - at beginning (e.g. chmod -x testfile). Remove
// the option and save it for later, after parsing is finished.
let mut negative_option = None;
for i in 0..args.len() {
if let Some(first) = args[i].chars().nth(0) {
if first!= '-' {
continue;
}
if let Some(second) = args[i].chars().nth(1) {
match second {
'r' | 'w' | 'x' | 'X' |'s' | 't' | 'u' | 'g' | 'o' | '0'... '7' => {
negative_option = Some(args.remove(i));
break;
},
_ => {}
}
}
}
}
let mut matches = match opts.parse(&args[1..]) {
Ok(m) => m,
Err(f) => { crash!(1, "{}", f) }
};
if matches.opt_present("help") {
let msg = format!("{name} {version}
Usage:
{program} [OPTION]... MODE[,MODE]... FILE...
{program} [OPTION]... OCTAL-MODE FILE...
{program} [OPTION]... --reference=RFILE FILE...
Change the mode of each FILE to MODE.
With --reference, change the mode of each FILE to that of RFILE.
Each MODE is of the form '[ugoa]*([-+=]([rwxXst]*|[ugo]))+|[-+=]?[0-7]+'.",
name = NAME, version = VERSION, program = NAME);
print!("{}", opts.usage(&msg));
return 0;
} else if matches.opt_present("version") {
println!("{} {}", NAME, VERSION);
} else if matches.free.is_empty() {
show_error!("missing an argument");
show_error!("for help, try '{} --help'", NAME);
return 1;
} else {
let changes = matches.opt_present("changes");
let quiet = matches.opt_present("quiet");
let verbose = matches.opt_present("verbose");
let preserve_root = matches.opt_present("preserve-root");
let recursive = matches.opt_present("recursive");
let fmode = matches.opt_str("reference").and_then(|fref| {
let s = CString::new(fref).unwrap_or_else( |_| {
crash!(1, "reference file name contains internal nul byte")
});
let mut stat : libc::stat = unsafe { mem::uninitialized() };
let statres = unsafe { libc::stat(s.as_ptr() as *const _, &mut stat as *mut libc::stat) };
if statres == 0 {
Some(stat.st_mode)
} else {
crash!(1, "cannot stat attribues of '{}': {}", matches.opt_str("reference").unwrap(), io::Error::last_os_error())
}
});
let cmode =
if fmode.is_none() {
// If there was a negative option, now it's a good time to
// use it.
if negative_option.is_some() {
negative_option
} else {
Some(matches.free.remove(0))
}
} else {
None
};
match chmod(matches.free, changes, quiet, verbose, preserve_root,
recursive, fmode, cmode.as_ref()) {
Ok(()) => {}
Err(e) => return e
}
}
0
}
fn chmod(files: Vec<String>, changes: bool, quiet: bool, verbose: bool, preserve_root: bool, recursive: bool, fmode: Option<libc::mode_t>, cmode: Option<&String>) -> Result<(), i32> {
let mut r = Ok(());
for filename in &files {
let filename = &filename[..];
let file = Path::new(filename);
if file.exists() {
if file.is_dir() {
if!preserve_root || filename!= "/" {
if recursive {
let walk_dir = match Walker::new(&file) {
Ok(m) => m,
Err(f) => {
crash!(1, "{}", f.to_string());
}
};
// XXX: here (and elsewhere) we see that this impl will have issues
// with non-UTF-8 filenames. Using OsString won't fix this because
// on Windows OsStrings cannot be built out of non-UTF-8 chars. One
// possible fix is to use CStrings rather than Strings in the args
// to chmod() and chmod_file().
r = chmod(walk_dir.filter_map(|x| match x {
Ok(o) => match o.path().into_os_string().to_str() {
Some(s) => Some(s.to_owned()),
None => None,
},
Err(_) => None,
}).collect(),
changes, quiet, verbose, preserve_root, recursive, fmode, cmode).and(r);
r = chmod_file(&file, filename, changes, quiet, verbose, fmode, cmode).and(r);
}
} else {
show_error!("could not change permissions of directory '{}'",
filename);
r = Err(1);
}
} else {
r = chmod_file(&file, filename, changes, quiet, verbose, fmode, cmode).and(r);
}
} else {
show_error!("no such file or directory '{}'", filename);
r = Err(1);
}
}
r
}
#[cfg(windows)]
fn chmod_file(file: &Path, name: &str, changes: bool, quiet: bool, verbose: bool, fmode: Option<libc::mode_t>, cmode: Option<&String>) -> Result<(), i32> {
// chmod is useless on Windows
// it doesn't set any permissions at all
// instead it just sets the readonly attribute on the file
Err(0)
}
#[cfg(unix)]
fn chmod_file(file: &Path, name: &str, changes: bool, quiet: bool, verbose: bool, fmode: Option<libc::mode_t>, cmode: Option<&String>) -> Result<(), i32> {
let path = CString::new(name).unwrap_or_else(|e| panic!("{}", e));
let mut stat: libc::stat = unsafe { mem::uninitialized() };
let statres = unsafe { libc::stat(path.as_ptr(), &mut stat as *mut libc::stat) };
let mut fperm =
if statres == 0 {
stat.st_mode & 0o7777
} else {
if!quiet {
show_error!("{}", io::Error::last_os_error());
}
return Err(1);
};
match fmode {
Some(mode) => try!(change_file(fperm, mode, file, &path, verbose, changes, quiet)),
None => {
for mode in cmode.unwrap().split(',') { // cmode is guaranteed to be Some in this case
let arr: &[char] = &['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
let result =
if mode.contains(arr) {
parse_numeric(fperm, mode)
} else {
parse_symbolic(fperm, mode, file)
};
match result {
Ok(mode) => {
try!(change_file(fperm, mode, file, &path, verbose, changes, quiet));
fperm = mode;
}
Err(f) => {
if!quiet {
show_error!("{}", f);
}
return Err(1);
}
}
}
}
}
Ok(())
}
fn parse_numeric(fperm: libc::mode_t, mut mode: &str) -> Result<libc::mode_t, String> {
let (op, pos) = try!(parse_op(mode, Some('=')));
mode = mode[pos..].trim_left_matches('0');
if mode.len() > 4 {
Err(format!("mode is too large ({} > 7777)", mode))
} else {
match libc::mode_t::from_str_radix(mode, 8) {
Ok(change) => {
Ok(match op {
'+' => fperm | change,
'-' => fperm &!change,
'=' => change,
_ => unreachable!()
})
}
Err(err) => Err(err.description().to_owned())
}
}
}
fn parse_symbolic(mut fperm: libc::mode_t, mut mode: &str, file: &Path) -> Result<libc::mode_t, String> {
let (mask, pos) = parse_levels(mode);
if pos == mode.len() {
return Err(format!("invalid mode ({})", mode));
}
mode = &mode[pos..];
while mode.len() > 0 {
let (op, pos) = try!(parse_op(mode, None));
mode = &mode[pos..];
let (srwx, pos) = parse_change(mode, fperm, file);
mode = &mode[pos..];
match op {
'+' => fperm |= srwx & mask,
'-' => fperm &=!(srwx & mask),
'=' => fperm = (fperm &!mask) | (srwx & mask),
_ => unreachable!()
}
}
Ok(fperm)
}
fn parse_levels(mode: &str) -> (libc::mode_t, usize) {
let mut mask = 0;
let mut pos = 0;
for ch in mode.chars() {
mask |= match ch {
'u' => 0o7700,
'g' => 0o7070,
'o' => 0o7007,
'a' => 0o7777,
_ => break
};
pos += 1;
}
if pos == 0 {
mask = 0o7777; // default to 'a'
}
(mask, pos)
}
fn parse_op(mode: &str, default: Option<char>) -> Result<(char, usize), String> {
match mode.chars().next() {
Some(ch) => match ch {
'+' | '-' | '=' => Ok((ch, 1)),
_ => match default {
Some(ch) => Ok((ch, 0)),
None => Err(format!("invalid operator (expected +, -, or =, but found {})", ch))
}
},
None => Err("unexpected end of mode".to_owned())
}
}
fn parse_change(mode: &str, fperm: libc::mode_t, file: &Path) -> (libc::mode_t, usize) {
let mut srwx = fperm & 0o7000;
let mut pos = 0;
for ch in mode.chars() {
match ch {
'r' => srwx |= 0o444,
'w' => srwx |= 0o222,
'x' => srwx |= 0o111,
'X' => {
if file.is_dir() || (fperm & 0o0111)!= 0 {
srwx |= 0o111
}
}
's' => srwx |= 0o4000 | 0o2000,
't' => srwx |= 0o1000,
'u' => srwx = (fperm & 0o700) | ((fperm >> 3) & 0o070) | ((fperm >> 6) & 0o007),
'g' => srwx = ((fperm << 3) & 0o700) | (fperm & 0o070) | ((fperm >> 3) & 0o007),
'o' => srwx = ((fperm << 6) & 0o700) | ((fperm << 3) & 0o070) | (fperm & 0o007),
_ => break
};
pos += 1;
}
if pos == 0 {
srwx = 0;
}
(srwx, pos)
}
fn change_file(fperm: libc::mode_t, mode: libc::mode_t, file: &Path, path: &CString, verbose: bool, changes: bool, quiet: bool) -> Result<(), i32>
|
}
|
{
if fperm == mode {
if verbose && !changes {
show_info!("mode of '{}' retained as {:o}", file.display(), fperm);
}
Ok(())
} else if unsafe { libc::chmod(path.as_ptr(), mode) } == 0 {
if verbose || changes {
show_info!("mode of '{}' changed from {:o} to {:o}", file.display(), fperm, mode);
}
Ok(())
} else {
if !quiet {
show_error!("{}", io::Error::last_os_error());
}
if verbose {
show_info!("failed to change mode of file '{}' from {:o} to {:o}", file.display(), fperm, mode);
}
return Err(1);
}
|
identifier_body
|
chmod.rs
|
#![crate_name = "uu_chmod"]
/*
* This file is part of the uutils coreutils package.
*
* (c) Arcterus <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
extern crate getopts;
extern crate libc;
extern crate walker;
#[macro_use]
extern crate uucore;
use getopts::Options;
use std::error::Error;
use std::ffi::CString;
use std::io::{self, Write};
use std::mem;
use std::path::Path;
use walker::Walker;
const NAME: &'static str = "chmod";
const VERSION: &'static str = env!("CARGO_PKG_VERSION");
pub fn uumain(mut args: Vec<String>) -> i32 {
let mut opts = Options::new();
opts.optflag("c", "changes", "like verbose but report only when a change is made (unimplemented)");
opts.optflag("f", "quiet", "suppress most error messages (unimplemented)"); // TODO: support --silent
opts.optflag("v", "verbose", "output a diagnostic for every file processed (unimplemented)");
opts.optflag("", "no-preserve-root", "do not treat '/' specially (the default)");
opts.optflag("", "preserve-root", "fail to operate recursively on '/'");
opts.optopt("", "reference", "use RFILE's mode instead of MODE values", "RFILE");
opts.optflag("R", "recursive", "change files and directories recursively");
opts.optflag("h", "help", "display this help and exit");
opts.optflag("V", "version", "output version information and exit");
// sanitize input for - at beginning (e.g. chmod -x testfile). Remove
// the option and save it for later, after parsing is finished.
let mut negative_option = None;
for i in 0..args.len() {
if let Some(first) = args[i].chars().nth(0) {
if first!= '-' {
continue;
}
if let Some(second) = args[i].chars().nth(1) {
match second {
'r' | 'w' | 'x' | 'X' |'s' | 't' | 'u' | 'g' | 'o' | '0'... '7' => {
negative_option = Some(args.remove(i));
break;
},
_ => {}
}
}
}
}
let mut matches = match opts.parse(&args[1..]) {
Ok(m) => m,
Err(f) => { crash!(1, "{}", f) }
};
if matches.opt_present("help") {
|
let msg = format!("{name} {version}
Usage:
{program} [OPTION]... MODE[,MODE]... FILE...
{program} [OPTION]... OCTAL-MODE FILE...
{program} [OPTION]... --reference=RFILE FILE...
Change the mode of each FILE to MODE.
With --reference, change the mode of each FILE to that of RFILE.
Each MODE is of the form '[ugoa]*([-+=]([rwxXst]*|[ugo]))+|[-+=]?[0-7]+'.",
name = NAME, version = VERSION, program = NAME);
print!("{}", opts.usage(&msg));
return 0;
} else if matches.opt_present("version") {
println!("{} {}", NAME, VERSION);
} else if matches.free.is_empty() {
show_error!("missing an argument");
show_error!("for help, try '{} --help'", NAME);
return 1;
} else {
let changes = matches.opt_present("changes");
let quiet = matches.opt_present("quiet");
let verbose = matches.opt_present("verbose");
let preserve_root = matches.opt_present("preserve-root");
let recursive = matches.opt_present("recursive");
let fmode = matches.opt_str("reference").and_then(|fref| {
let s = CString::new(fref).unwrap_or_else( |_| {
crash!(1, "reference file name contains internal nul byte")
});
let mut stat : libc::stat = unsafe { mem::uninitialized() };
let statres = unsafe { libc::stat(s.as_ptr() as *const _, &mut stat as *mut libc::stat) };
if statres == 0 {
Some(stat.st_mode)
} else {
crash!(1, "cannot stat attribues of '{}': {}", matches.opt_str("reference").unwrap(), io::Error::last_os_error())
}
});
let cmode =
if fmode.is_none() {
// If there was a negative option, now it's a good time to
// use it.
if negative_option.is_some() {
negative_option
} else {
Some(matches.free.remove(0))
}
} else {
None
};
match chmod(matches.free, changes, quiet, verbose, preserve_root,
recursive, fmode, cmode.as_ref()) {
Ok(()) => {}
Err(e) => return e
}
}
0
}
fn chmod(files: Vec<String>, changes: bool, quiet: bool, verbose: bool, preserve_root: bool, recursive: bool, fmode: Option<libc::mode_t>, cmode: Option<&String>) -> Result<(), i32> {
let mut r = Ok(());
for filename in &files {
let filename = &filename[..];
let file = Path::new(filename);
if file.exists() {
if file.is_dir() {
if!preserve_root || filename!= "/" {
if recursive {
let walk_dir = match Walker::new(&file) {
Ok(m) => m,
Err(f) => {
crash!(1, "{}", f.to_string());
}
};
// XXX: here (and elsewhere) we see that this impl will have issues
// with non-UTF-8 filenames. Using OsString won't fix this because
// on Windows OsStrings cannot be built out of non-UTF-8 chars. One
// possible fix is to use CStrings rather than Strings in the args
// to chmod() and chmod_file().
r = chmod(walk_dir.filter_map(|x| match x {
Ok(o) => match o.path().into_os_string().to_str() {
Some(s) => Some(s.to_owned()),
None => None,
},
Err(_) => None,
}).collect(),
changes, quiet, verbose, preserve_root, recursive, fmode, cmode).and(r);
r = chmod_file(&file, filename, changes, quiet, verbose, fmode, cmode).and(r);
}
} else {
show_error!("could not change permissions of directory '{}'",
filename);
r = Err(1);
}
} else {
r = chmod_file(&file, filename, changes, quiet, verbose, fmode, cmode).and(r);
}
} else {
show_error!("no such file or directory '{}'", filename);
r = Err(1);
}
}
r
}
#[cfg(windows)]
fn chmod_file(file: &Path, name: &str, changes: bool, quiet: bool, verbose: bool, fmode: Option<libc::mode_t>, cmode: Option<&String>) -> Result<(), i32> {
// chmod is useless on Windows
// it doesn't set any permissions at all
// instead it just sets the readonly attribute on the file
Err(0)
}
#[cfg(unix)]
fn chmod_file(file: &Path, name: &str, changes: bool, quiet: bool, verbose: bool, fmode: Option<libc::mode_t>, cmode: Option<&String>) -> Result<(), i32> {
let path = CString::new(name).unwrap_or_else(|e| panic!("{}", e));
let mut stat: libc::stat = unsafe { mem::uninitialized() };
let statres = unsafe { libc::stat(path.as_ptr(), &mut stat as *mut libc::stat) };
let mut fperm =
if statres == 0 {
stat.st_mode & 0o7777
} else {
if!quiet {
show_error!("{}", io::Error::last_os_error());
}
return Err(1);
};
match fmode {
Some(mode) => try!(change_file(fperm, mode, file, &path, verbose, changes, quiet)),
None => {
for mode in cmode.unwrap().split(',') { // cmode is guaranteed to be Some in this case
let arr: &[char] = &['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
let result =
if mode.contains(arr) {
parse_numeric(fperm, mode)
} else {
parse_symbolic(fperm, mode, file)
};
match result {
Ok(mode) => {
try!(change_file(fperm, mode, file, &path, verbose, changes, quiet));
fperm = mode;
}
Err(f) => {
if!quiet {
show_error!("{}", f);
}
return Err(1);
}
}
}
}
}
Ok(())
}
fn parse_numeric(fperm: libc::mode_t, mut mode: &str) -> Result<libc::mode_t, String> {
let (op, pos) = try!(parse_op(mode, Some('=')));
mode = mode[pos..].trim_left_matches('0');
if mode.len() > 4 {
Err(format!("mode is too large ({} > 7777)", mode))
} else {
match libc::mode_t::from_str_radix(mode, 8) {
Ok(change) => {
Ok(match op {
'+' => fperm | change,
'-' => fperm &!change,
'=' => change,
_ => unreachable!()
})
}
Err(err) => Err(err.description().to_owned())
}
}
}
fn parse_symbolic(mut fperm: libc::mode_t, mut mode: &str, file: &Path) -> Result<libc::mode_t, String> {
let (mask, pos) = parse_levels(mode);
if pos == mode.len() {
return Err(format!("invalid mode ({})", mode));
}
mode = &mode[pos..];
while mode.len() > 0 {
let (op, pos) = try!(parse_op(mode, None));
mode = &mode[pos..];
let (srwx, pos) = parse_change(mode, fperm, file);
mode = &mode[pos..];
match op {
'+' => fperm |= srwx & mask,
'-' => fperm &=!(srwx & mask),
'=' => fperm = (fperm &!mask) | (srwx & mask),
_ => unreachable!()
}
}
Ok(fperm)
}
fn parse_levels(mode: &str) -> (libc::mode_t, usize) {
let mut mask = 0;
let mut pos = 0;
for ch in mode.chars() {
mask |= match ch {
'u' => 0o7700,
'g' => 0o7070,
'o' => 0o7007,
'a' => 0o7777,
_ => break
};
pos += 1;
}
if pos == 0 {
mask = 0o7777; // default to 'a'
}
(mask, pos)
}
fn parse_op(mode: &str, default: Option<char>) -> Result<(char, usize), String> {
match mode.chars().next() {
Some(ch) => match ch {
'+' | '-' | '=' => Ok((ch, 1)),
_ => match default {
Some(ch) => Ok((ch, 0)),
None => Err(format!("invalid operator (expected +, -, or =, but found {})", ch))
}
},
None => Err("unexpected end of mode".to_owned())
}
}
fn parse_change(mode: &str, fperm: libc::mode_t, file: &Path) -> (libc::mode_t, usize) {
let mut srwx = fperm & 0o7000;
let mut pos = 0;
for ch in mode.chars() {
match ch {
'r' => srwx |= 0o444,
'w' => srwx |= 0o222,
'x' => srwx |= 0o111,
'X' => {
if file.is_dir() || (fperm & 0o0111)!= 0 {
srwx |= 0o111
}
}
's' => srwx |= 0o4000 | 0o2000,
't' => srwx |= 0o1000,
'u' => srwx = (fperm & 0o700) | ((fperm >> 3) & 0o070) | ((fperm >> 6) & 0o007),
'g' => srwx = ((fperm << 3) & 0o700) | (fperm & 0o070) | ((fperm >> 3) & 0o007),
'o' => srwx = ((fperm << 6) & 0o700) | ((fperm << 3) & 0o070) | (fperm & 0o007),
_ => break
};
pos += 1;
}
if pos == 0 {
srwx = 0;
}
(srwx, pos)
}
fn change_file(fperm: libc::mode_t, mode: libc::mode_t, file: &Path, path: &CString, verbose: bool, changes: bool, quiet: bool) -> Result<(), i32> {
if fperm == mode {
if verbose &&!changes {
show_info!("mode of '{}' retained as {:o}", file.display(), fperm);
}
Ok(())
} else if unsafe { libc::chmod(path.as_ptr(), mode) } == 0 {
if verbose || changes {
show_info!("mode of '{}' changed from {:o} to {:o}", file.display(), fperm, mode);
}
Ok(())
} else {
if!quiet {
show_error!("{}", io::Error::last_os_error());
}
if verbose {
show_info!("failed to change mode of file '{}' from {:o} to {:o}", file.display(), fperm, mode);
}
return Err(1);
}
}
|
random_line_split
|
|
outline.mako.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/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<% from data import Method %>
<% data.new_style_struct("Outline",
inherited=False,
additional_methods=[Method("outline_has_nonzero_width", "bool")]) %>
// TODO(pcwalton): `invert`
${helpers.predefined_type("outline-color", "Color", "computed_value::T::currentcolor()",
initial_specified_value="specified::Color::currentcolor()",
animation_value_type="IntermediateColor", need_clone=True,
ignored_when_colors_disabled=True,
spec="https://drafts.csswg.org/css-ui/#propdef-outline-color")}
<%helpers:longhand name="outline-style" animation_value_type="discrete"
spec="https://drafts.csswg.org/css-ui/#propdef-outline-style">
use values::specified::BorderStyle;
pub type SpecifiedValue = Either<Auto, BorderStyle>;
impl SpecifiedValue {
#[inline]
pub fn none_or_hidden(&self) -> bool {
match *self {
Either::First(ref _auto) => false,
Either::Second(ref border_style) => border_style.none_or_hidden()
}
}
}
#[inline]
pub fn get_initial_value() -> computed_value::T {
Either::Second(BorderStyle::none)
}
#[inline]
pub fn get_initial_specified_value() -> SpecifiedValue {
Either::Second(BorderStyle::none)
}
pub mod computed_value {
pub type T = super::SpecifiedValue;
}
pub fn
|
<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>)
-> Result<SpecifiedValue, ParseError<'i>> {
SpecifiedValue::parse(context, input)
.and_then(|result| {
if let Either::Second(BorderStyle::hidden) = result {
// The outline-style property accepts the same values as
// border-style, except that 'hidden' is not a legal outline
// style.
Err(SelectorParseError::UnexpectedIdent("hidden".into()).into())
} else {
Ok(result)
}
})
}
</%helpers:longhand>
${helpers.predefined_type("outline-width",
"BorderSideWidth",
"Au::from_px(3)",
initial_specified_value="specified::BorderSideWidth::Medium",
computed_type="::app_units::Au",
animation_value_type="ComputedValue",
spec="https://drafts.csswg.org/css-ui/#propdef-outline-width")}
// The -moz-outline-radius-* properties are non-standard and not on a standards track.
% for corner in ["topleft", "topright", "bottomright", "bottomleft"]:
${helpers.predefined_type("-moz-outline-radius-" + corner, "BorderCornerRadius",
"computed::LengthOrPercentage::zero().into()",
products="gecko",
boxed=True,
animation_value_type="ComputedValue",
spec="Nonstandard (https://developer.mozilla.org/en-US/docs/Web/CSS/-moz-outline-radius)")}
% endfor
${helpers.predefined_type("outline-offset", "Length", "Au(0)", products="servo gecko",
animation_value_type="ComputedValue",
spec="https://drafts.csswg.org/css-ui/#propdef-outline-offset")}
|
parse
|
identifier_name
|
outline.mako.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/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<% from data import Method %>
<% data.new_style_struct("Outline",
inherited=False,
additional_methods=[Method("outline_has_nonzero_width", "bool")]) %>
// TODO(pcwalton): `invert`
${helpers.predefined_type("outline-color", "Color", "computed_value::T::currentcolor()",
initial_specified_value="specified::Color::currentcolor()",
animation_value_type="IntermediateColor", need_clone=True,
ignored_when_colors_disabled=True,
spec="https://drafts.csswg.org/css-ui/#propdef-outline-color")}
<%helpers:longhand name="outline-style" animation_value_type="discrete"
spec="https://drafts.csswg.org/css-ui/#propdef-outline-style">
use values::specified::BorderStyle;
pub type SpecifiedValue = Either<Auto, BorderStyle>;
impl SpecifiedValue {
#[inline]
pub fn none_or_hidden(&self) -> bool {
match *self {
Either::First(ref _auto) => false,
Either::Second(ref border_style) => border_style.none_or_hidden()
}
}
}
#[inline]
pub fn get_initial_value() -> computed_value::T
|
#[inline]
pub fn get_initial_specified_value() -> SpecifiedValue {
Either::Second(BorderStyle::none)
}
pub mod computed_value {
pub type T = super::SpecifiedValue;
}
pub fn parse<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>)
-> Result<SpecifiedValue, ParseError<'i>> {
SpecifiedValue::parse(context, input)
.and_then(|result| {
if let Either::Second(BorderStyle::hidden) = result {
// The outline-style property accepts the same values as
// border-style, except that 'hidden' is not a legal outline
// style.
Err(SelectorParseError::UnexpectedIdent("hidden".into()).into())
} else {
Ok(result)
}
})
}
</%helpers:longhand>
${helpers.predefined_type("outline-width",
"BorderSideWidth",
"Au::from_px(3)",
initial_specified_value="specified::BorderSideWidth::Medium",
computed_type="::app_units::Au",
animation_value_type="ComputedValue",
spec="https://drafts.csswg.org/css-ui/#propdef-outline-width")}
// The -moz-outline-radius-* properties are non-standard and not on a standards track.
% for corner in ["topleft", "topright", "bottomright", "bottomleft"]:
${helpers.predefined_type("-moz-outline-radius-" + corner, "BorderCornerRadius",
"computed::LengthOrPercentage::zero().into()",
products="gecko",
boxed=True,
animation_value_type="ComputedValue",
spec="Nonstandard (https://developer.mozilla.org/en-US/docs/Web/CSS/-moz-outline-radius)")}
% endfor
${helpers.predefined_type("outline-offset", "Length", "Au(0)", products="servo gecko",
animation_value_type="ComputedValue",
spec="https://drafts.csswg.org/css-ui/#propdef-outline-offset")}
|
{
Either::Second(BorderStyle::none)
}
|
identifier_body
|
outline.mako.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/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<% from data import Method %>
<% data.new_style_struct("Outline",
inherited=False,
additional_methods=[Method("outline_has_nonzero_width", "bool")]) %>
// TODO(pcwalton): `invert`
${helpers.predefined_type("outline-color", "Color", "computed_value::T::currentcolor()",
initial_specified_value="specified::Color::currentcolor()",
animation_value_type="IntermediateColor", need_clone=True,
ignored_when_colors_disabled=True,
spec="https://drafts.csswg.org/css-ui/#propdef-outline-color")}
<%helpers:longhand name="outline-style" animation_value_type="discrete"
spec="https://drafts.csswg.org/css-ui/#propdef-outline-style">
use values::specified::BorderStyle;
pub type SpecifiedValue = Either<Auto, BorderStyle>;
impl SpecifiedValue {
#[inline]
pub fn none_or_hidden(&self) -> bool {
match *self {
Either::First(ref _auto) => false,
Either::Second(ref border_style) => border_style.none_or_hidden()
}
}
}
#[inline]
pub fn get_initial_value() -> computed_value::T {
Either::Second(BorderStyle::none)
}
#[inline]
pub fn get_initial_specified_value() -> SpecifiedValue {
Either::Second(BorderStyle::none)
}
pub mod computed_value {
pub type T = super::SpecifiedValue;
}
pub fn parse<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>)
-> Result<SpecifiedValue, ParseError<'i>> {
SpecifiedValue::parse(context, input)
.and_then(|result| {
if let Either::Second(BorderStyle::hidden) = result {
// The outline-style property accepts the same values as
// border-style, except that 'hidden' is not a legal outline
// style.
Err(SelectorParseError::UnexpectedIdent("hidden".into()).into())
} else {
Ok(result)
}
})
|
"Au::from_px(3)",
initial_specified_value="specified::BorderSideWidth::Medium",
computed_type="::app_units::Au",
animation_value_type="ComputedValue",
spec="https://drafts.csswg.org/css-ui/#propdef-outline-width")}
// The -moz-outline-radius-* properties are non-standard and not on a standards track.
% for corner in ["topleft", "topright", "bottomright", "bottomleft"]:
${helpers.predefined_type("-moz-outline-radius-" + corner, "BorderCornerRadius",
"computed::LengthOrPercentage::zero().into()",
products="gecko",
boxed=True,
animation_value_type="ComputedValue",
spec="Nonstandard (https://developer.mozilla.org/en-US/docs/Web/CSS/-moz-outline-radius)")}
% endfor
${helpers.predefined_type("outline-offset", "Length", "Au(0)", products="servo gecko",
animation_value_type="ComputedValue",
spec="https://drafts.csswg.org/css-ui/#propdef-outline-offset")}
|
}
</%helpers:longhand>
${helpers.predefined_type("outline-width",
"BorderSideWidth",
|
random_line_split
|
into_bits.rs
|
//! Implementation of `FromBits` and `IntoBits`.
/// Safe lossless bitwise conversion from `T` to `Self`.
pub trait FromBits<T>: crate::marker::Sized {
/// Safe lossless bitwise transmute from `T` to `Self`.
fn from_bits(t: T) -> Self;
}
/// Safe lossless bitwise conversion from `Self` to `T`.
pub trait IntoBits<T>: crate::marker::Sized {
/// Safe lossless bitwise transmute from `self` to `T`.
fn into_bits(self) -> T;
}
/// `FromBits` implies `IntoBits`.
impl<T, U> IntoBits<U> for T
where
U: FromBits<T>,
{
#[inline]
fn into_bits(self) -> U {
debug_assert!(
crate::mem::size_of::<Self>() == crate::mem::size_of::<U>()
|
/// `FromBits` and `IntoBits` are reflexive
impl<T> FromBits<T> for T {
#[inline]
fn from_bits(t: Self) -> Self {
t
}
}
#[macro_use]
mod macros;
mod v16;
pub use self::v16::*;
mod v32;
pub use self::v32::*;
mod v64;
pub use self::v64::*;
mod v128;
pub use self::v128::*;
mod v256;
pub use self::v256::*;
mod v512;
pub use self::v512::*;
mod arch_specific;
pub use self::arch_specific::*;
|
);
U::from_bits(self)
}
}
|
random_line_split
|
into_bits.rs
|
//! Implementation of `FromBits` and `IntoBits`.
/// Safe lossless bitwise conversion from `T` to `Self`.
pub trait FromBits<T>: crate::marker::Sized {
/// Safe lossless bitwise transmute from `T` to `Self`.
fn from_bits(t: T) -> Self;
}
/// Safe lossless bitwise conversion from `Self` to `T`.
pub trait IntoBits<T>: crate::marker::Sized {
/// Safe lossless bitwise transmute from `self` to `T`.
fn into_bits(self) -> T;
}
/// `FromBits` implies `IntoBits`.
impl<T, U> IntoBits<U> for T
where
U: FromBits<T>,
{
#[inline]
fn into_bits(self) -> U
|
}
/// `FromBits` and `IntoBits` are reflexive
impl<T> FromBits<T> for T {
#[inline]
fn from_bits(t: Self) -> Self {
t
}
}
#[macro_use]
mod macros;
mod v16;
pub use self::v16::*;
mod v32;
pub use self::v32::*;
mod v64;
pub use self::v64::*;
mod v128;
pub use self::v128::*;
mod v256;
pub use self::v256::*;
mod v512;
pub use self::v512::*;
mod arch_specific;
pub use self::arch_specific::*;
|
{
debug_assert!(
crate::mem::size_of::<Self>() == crate::mem::size_of::<U>()
);
U::from_bits(self)
}
|
identifier_body
|
into_bits.rs
|
//! Implementation of `FromBits` and `IntoBits`.
/// Safe lossless bitwise conversion from `T` to `Self`.
pub trait FromBits<T>: crate::marker::Sized {
/// Safe lossless bitwise transmute from `T` to `Self`.
fn from_bits(t: T) -> Self;
}
/// Safe lossless bitwise conversion from `Self` to `T`.
pub trait IntoBits<T>: crate::marker::Sized {
/// Safe lossless bitwise transmute from `self` to `T`.
fn into_bits(self) -> T;
}
/// `FromBits` implies `IntoBits`.
impl<T, U> IntoBits<U> for T
where
U: FromBits<T>,
{
#[inline]
fn
|
(self) -> U {
debug_assert!(
crate::mem::size_of::<Self>() == crate::mem::size_of::<U>()
);
U::from_bits(self)
}
}
/// `FromBits` and `IntoBits` are reflexive
impl<T> FromBits<T> for T {
#[inline]
fn from_bits(t: Self) -> Self {
t
}
}
#[macro_use]
mod macros;
mod v16;
pub use self::v16::*;
mod v32;
pub use self::v32::*;
mod v64;
pub use self::v64::*;
mod v128;
pub use self::v128::*;
mod v256;
pub use self::v256::*;
mod v512;
pub use self::v512::*;
mod arch_specific;
pub use self::arch_specific::*;
|
into_bits
|
identifier_name
|
borrow.rs
|
// 此函数拥有 box 的所有权并销毁它
fn eat_box_i32(boxed_i32: Box<i32>) {
println!("Destroying box that contains {}", boxed_i32);
}
// 此函数借用了一个 i32 类型
fn borrow_i32(borrowed_i32: &i32) {
println!("This int is: {}", borrowed_i32);
}
fn main() {
// 创建一个装箱的 i32 类型,以及一个存在栈中的 i32 类型。
|
// box 现在可以放弃 `eat_i32` 的所有权且可以销毁
eat_i32(boxed_i32);
}
|
let boxed_int = Box::new(5_i32);
let stacked_i32 = 6_i32;
// 借用了 box 的内容,但没有取得所有权,所以 box 的内容可以
// 再次借用。
borrow_i32(&boxed_i32);
borrow_i32(&tacked_i32);
{
// 给出一个指向 box 里面所包含数据的引用
let _ref_to_i32: &i32 = &boxed_i32;
// 报错!
// 当 `boxed_i32` 里面的值被借用时,不能销毁 `boxed_int`。
eat_box_i32(boxed_i32);
// 改正 ^ 注释掉此行
// `_ref_to_i32` 离开作用域且不再被借用。
}
|
identifier_body
|
borrow.rs
|
// 此函数拥有 box 的所有权并销毁它
fn eat_box_i32(boxed_i32: Box<i32>) {
println!("Destroying box that contains {}", boxed_i32);
}
// 此函数借用了一个 i32 类型
fn borrow_i32(borrowed_i32: &i32) {
|
fn main() {
// 创建一个装箱的 i32 类型,以及一个存在栈中的 i32 类型。
let boxed_int = Box::new(5_i32);
let stacked_i32 = 6_i32;
// 借用了 box 的内容,但没有取得所有权,所以 box 的内容可以
// 再次借用。
borrow_i32(&boxed_i32);
borrow_i32(&tacked_i32);
{
// 给出一个指向 box 里面所包含数据的引用
let _ref_to_i32: &i32 = &boxed_i32;
// 报错!
// 当 `boxed_i32` 里面的值被借用时,不能销毁 `boxed_int`。
eat_box_i32(boxed_i32);
// 改正 ^ 注释掉此行
// `_ref_to_i32` 离开作用域且不再被借用。
}
// box 现在可以放弃 `eat_i32` 的所有权且可以销毁
eat_i32(boxed_i32);
}
|
println!("This int is: {}", borrowed_i32);
}
|
random_line_split
|
borrow.rs
|
// 此函数拥有 box 的所有权并销毁它
fn eat_box_i32(boxed_i32: Box<i32>) {
println!("Destroying box that contains {}", boxed_i32);
}
// 此函数借用了一个 i32 类型
fn borrow_i32(borrowed_i32: &i32) {
println!(
|
is: {}", borrowed_i32);
}
fn main() {
// 创建一个装箱的 i32 类型,以及一个存在栈中的 i32 类型。
let boxed_int = Box::new(5_i32);
let stacked_i32 = 6_i32;
// 借用了 box 的内容,但没有取得所有权,所以 box 的内容可以
// 再次借用。
borrow_i32(&boxed_i32);
borrow_i32(&tacked_i32);
{
// 给出一个指向 box 里面所包含数据的引用
let _ref_to_i32: &i32 = &boxed_i32;
// 报错!
// 当 `boxed_i32` 里面的值被借用时,不能销毁 `boxed_int`。
eat_box_i32(boxed_i32);
// 改正 ^ 注释掉此行
// `_ref_to_i32` 离开作用域且不再被借用。
}
// box 现在可以放弃 `eat_i32` 的所有权且可以销毁
eat_i32(boxed_i32);
}
|
"This int
|
identifier_name
|
braille.rs
|
// Copyright (c) 2016 Patrick Burroughs <[email protected]>.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// https://www.apache.org/licenses/LICENSE-2.0>, or the MIT license
// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option.
// This file may not be copied, modified, or distributed except
// according to those terms.
use super::{Graph, Result};
use super::GraphErrorKind::NoInput;
use super::ParseGraphError as Error;
use std::cmp::max;
const EMPTY: u32 = 0x2800;
const CHAR: [&'static [&'static [u32]]; 4] =
[ &[ &[0x00, 0x40, 0x44, 0x46, 0x47],
&[0x00, 0x80, 0xA0, 0xB0, 0xB8],],
&[ &[0x00, 0x01, 0x09],
&[0x00, 0x02, 0x12],
&[0x00, 0x04, 0x24],
&[0x00, 0x40, 0xC0],],
&[ &[0x00, 0x01, 0x03, 0x07, 0x47],
&[0x00, 0x08, 0x18, 0x38, 0xB8],],
&[ &[0x00, 0x08, 0x09],
&[0x00, 0x10, 0x12],
&[0x00, 0x20, 0x24],
&[0x00, 0x80, 0xC0],],
];
pub fn horizontal_graph(reverse: bool, input: Vec<usize>) -> Result<Graph> {
let blocks = input.len() / 2 + if input.len() % 2 > 0 { 1 } else { 0 };
let lines = max((try!(input.iter().max().ok_or(Error { kind: NoInput })) + 3) / 4, 1);
let char = if reverse
|
else { 0 };
let mut output: Graph = vec![vec![EMPTY; blocks]; lines];
for (block,chunk) in input.chunks(2).collect::<Vec<&[usize]>>().iter().enumerate() {
for (index,value) in chunk.iter().enumerate() {
for line in 0..lines {
let partial = value.saturating_sub(line * 4);
let insert = if partial > 4 { 4 } else { partial };
output[line][block] += CHAR[char][index][insert]
}
}
};
if!reverse {
output.reverse()
};
Ok(output)
}
pub fn vertical_graph(reverse: bool, input: Vec<usize>) -> Result<Graph> {
let blocks = max((try!(input.iter().max().ok_or(Error { kind: NoInput })) + 1) / 2, 1);
let lines = input.len() / 4 + if input.len() % 4 > 0 { 1 } else { 0 };
let char = if reverse { 3 } else { 1 };
let mut output: Graph = vec![vec![EMPTY; blocks]; lines];
for (line, chunk) in input.chunks(4).collect::<Vec<&[usize]>>().iter().enumerate() {
for (index,value) in chunk.iter().enumerate() {
for block in 0..blocks {
let partial = value.saturating_sub(block * 2);
let insert = if partial > 2 { 2 } else { partial };
output[line][block] += CHAR[char][index][insert]
}
}
};
if reverse {
for line in 0..lines {
output[line].reverse()
}
};
Ok(output)
}
|
{ 2 }
|
conditional_block
|
braille.rs
|
// Copyright (c) 2016 Patrick Burroughs <[email protected]>.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// https://www.apache.org/licenses/LICENSE-2.0>, or the MIT license
// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option.
// This file may not be copied, modified, or distributed except
// according to those terms.
use super::{Graph, Result};
use super::GraphErrorKind::NoInput;
use super::ParseGraphError as Error;
use std::cmp::max;
const EMPTY: u32 = 0x2800;
const CHAR: [&'static [&'static [u32]]; 4] =
[ &[ &[0x00, 0x40, 0x44, 0x46, 0x47],
&[0x00, 0x80, 0xA0, 0xB0, 0xB8],],
&[ &[0x00, 0x01, 0x09],
&[0x00, 0x02, 0x12],
&[0x00, 0x04, 0x24],
&[0x00, 0x40, 0xC0],],
&[ &[0x00, 0x01, 0x03, 0x07, 0x47],
&[0x00, 0x08, 0x18, 0x38, 0xB8],],
&[ &[0x00, 0x08, 0x09],
&[0x00, 0x10, 0x12],
&[0x00, 0x20, 0x24],
&[0x00, 0x80, 0xC0],],
];
pub fn
|
(reverse: bool, input: Vec<usize>) -> Result<Graph> {
let blocks = input.len() / 2 + if input.len() % 2 > 0 { 1 } else { 0 };
let lines = max((try!(input.iter().max().ok_or(Error { kind: NoInput })) + 3) / 4, 1);
let char = if reverse { 2 } else { 0 };
let mut output: Graph = vec![vec![EMPTY; blocks]; lines];
for (block,chunk) in input.chunks(2).collect::<Vec<&[usize]>>().iter().enumerate() {
for (index,value) in chunk.iter().enumerate() {
for line in 0..lines {
let partial = value.saturating_sub(line * 4);
let insert = if partial > 4 { 4 } else { partial };
output[line][block] += CHAR[char][index][insert]
}
}
};
if!reverse {
output.reverse()
};
Ok(output)
}
pub fn vertical_graph(reverse: bool, input: Vec<usize>) -> Result<Graph> {
let blocks = max((try!(input.iter().max().ok_or(Error { kind: NoInput })) + 1) / 2, 1);
let lines = input.len() / 4 + if input.len() % 4 > 0 { 1 } else { 0 };
let char = if reverse { 3 } else { 1 };
let mut output: Graph = vec![vec![EMPTY; blocks]; lines];
for (line, chunk) in input.chunks(4).collect::<Vec<&[usize]>>().iter().enumerate() {
for (index,value) in chunk.iter().enumerate() {
for block in 0..blocks {
let partial = value.saturating_sub(block * 2);
let insert = if partial > 2 { 2 } else { partial };
output[line][block] += CHAR[char][index][insert]
}
}
};
if reverse {
for line in 0..lines {
output[line].reverse()
}
};
Ok(output)
}
|
horizontal_graph
|
identifier_name
|
braille.rs
|
// Copyright (c) 2016 Patrick Burroughs <[email protected]>.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// https://www.apache.org/licenses/LICENSE-2.0>, or the MIT license
// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option.
// This file may not be copied, modified, or distributed except
// according to those terms.
use super::{Graph, Result};
use super::GraphErrorKind::NoInput;
use super::ParseGraphError as Error;
use std::cmp::max;
const EMPTY: u32 = 0x2800;
const CHAR: [&'static [&'static [u32]]; 4] =
[ &[ &[0x00, 0x40, 0x44, 0x46, 0x47],
&[0x00, 0x80, 0xA0, 0xB0, 0xB8],],
&[ &[0x00, 0x01, 0x09],
&[0x00, 0x02, 0x12],
&[0x00, 0x04, 0x24],
&[0x00, 0x40, 0xC0],],
&[ &[0x00, 0x01, 0x03, 0x07, 0x47],
&[0x00, 0x08, 0x18, 0x38, 0xB8],],
&[ &[0x00, 0x08, 0x09],
&[0x00, 0x10, 0x12],
&[0x00, 0x20, 0x24],
&[0x00, 0x80, 0xC0],],
];
pub fn horizontal_graph(reverse: bool, input: Vec<usize>) -> Result<Graph>
|
};
Ok(output)
}
pub fn vertical_graph(reverse: bool, input: Vec<usize>) -> Result<Graph> {
let blocks = max((try!(input.iter().max().ok_or(Error { kind: NoInput })) + 1) / 2, 1);
let lines = input.len() / 4 + if input.len() % 4 > 0 { 1 } else { 0 };
let char = if reverse { 3 } else { 1 };
let mut output: Graph = vec![vec![EMPTY; blocks]; lines];
for (line, chunk) in input.chunks(4).collect::<Vec<&[usize]>>().iter().enumerate() {
for (index,value) in chunk.iter().enumerate() {
for block in 0..blocks {
let partial = value.saturating_sub(block * 2);
let insert = if partial > 2 { 2 } else { partial };
output[line][block] += CHAR[char][index][insert]
}
}
};
if reverse {
for line in 0..lines {
output[line].reverse()
}
};
Ok(output)
}
|
{
let blocks = input.len() / 2 + if input.len() % 2 > 0 { 1 } else { 0 };
let lines = max((try!(input.iter().max().ok_or(Error { kind: NoInput })) + 3) / 4, 1);
let char = if reverse { 2 } else { 0 };
let mut output: Graph = vec![vec![EMPTY; blocks]; lines];
for (block,chunk) in input.chunks(2).collect::<Vec<&[usize]>>().iter().enumerate() {
for (index,value) in chunk.iter().enumerate() {
for line in 0..lines {
let partial = value.saturating_sub(line * 4);
let insert = if partial > 4 { 4 } else { partial };
output[line][block] += CHAR[char][index][insert]
}
}
};
if !reverse {
output.reverse()
|
identifier_body
|
braille.rs
|
// Copyright (c) 2016 Patrick Burroughs <[email protected]>.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// https://www.apache.org/licenses/LICENSE-2.0>, or the MIT license
// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option.
// This file may not be copied, modified, or distributed except
// according to those terms.
use super::{Graph, Result};
use super::GraphErrorKind::NoInput;
use super::ParseGraphError as Error;
use std::cmp::max;
const EMPTY: u32 = 0x2800;
const CHAR: [&'static [&'static [u32]]; 4] =
[ &[ &[0x00, 0x40, 0x44, 0x46, 0x47],
&[0x00, 0x80, 0xA0, 0xB0, 0xB8],],
&[ &[0x00, 0x01, 0x09],
&[0x00, 0x02, 0x12],
&[0x00, 0x04, 0x24],
&[0x00, 0x40, 0xC0],],
&[ &[0x00, 0x01, 0x03, 0x07, 0x47],
&[0x00, 0x08, 0x18, 0x38, 0xB8],],
&[ &[0x00, 0x08, 0x09],
&[0x00, 0x10, 0x12],
&[0x00, 0x20, 0x24],
&[0x00, 0x80, 0xC0],],
];
pub fn horizontal_graph(reverse: bool, input: Vec<usize>) -> Result<Graph> {
let blocks = input.len() / 2 + if input.len() % 2 > 0 { 1 } else { 0 };
let lines = max((try!(input.iter().max().ok_or(Error { kind: NoInput })) + 3) / 4, 1);
let char = if reverse { 2 } else { 0 };
let mut output: Graph = vec![vec![EMPTY; blocks]; lines];
for (block,chunk) in input.chunks(2).collect::<Vec<&[usize]>>().iter().enumerate() {
for (index,value) in chunk.iter().enumerate() {
for line in 0..lines {
let partial = value.saturating_sub(line * 4);
let insert = if partial > 4 { 4 } else { partial };
output[line][block] += CHAR[char][index][insert]
}
}
};
if!reverse {
output.reverse()
};
Ok(output)
}
pub fn vertical_graph(reverse: bool, input: Vec<usize>) -> Result<Graph> {
let blocks = max((try!(input.iter().max().ok_or(Error { kind: NoInput })) + 1) / 2, 1);
|
for (line, chunk) in input.chunks(4).collect::<Vec<&[usize]>>().iter().enumerate() {
for (index,value) in chunk.iter().enumerate() {
for block in 0..blocks {
let partial = value.saturating_sub(block * 2);
let insert = if partial > 2 { 2 } else { partial };
output[line][block] += CHAR[char][index][insert]
}
}
};
if reverse {
for line in 0..lines {
output[line].reverse()
}
};
Ok(output)
}
|
let lines = input.len() / 4 + if input.len() % 4 > 0 { 1 } else { 0 };
let char = if reverse { 3 } else { 1 };
let mut output: Graph = vec![vec![EMPTY; blocks]; lines];
|
random_line_split
|
method-two-trait-defer-resolution-1.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.
// Test that we pick which version of `foo` to run based on the
// type that is (ultimately) inferred for `x`.
trait foo {
fn foo(&self) -> i32;
}
impl foo for Vec<u32> {
fn foo(&self) -> i32
|
}
impl foo for Vec<i32> {
fn foo(&self) -> i32 {2}
}
fn call_foo_uint() -> i32 {
let mut x = Vec::new();
let y = x.foo();
x.push(0u32);
y
}
fn call_foo_int() -> i32 {
let mut x = Vec::new();
let y = x.foo();
x.push(0i32);
y
}
fn main() {
assert_eq!(call_foo_uint(), 1);
assert_eq!(call_foo_int(), 2);
}
|
{1}
|
identifier_body
|
method-two-trait-defer-resolution-1.rs
|
//
// 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 that we pick which version of `foo` to run based on the
// type that is (ultimately) inferred for `x`.
trait foo {
fn foo(&self) -> i32;
}
impl foo for Vec<u32> {
fn foo(&self) -> i32 {1}
}
impl foo for Vec<i32> {
fn foo(&self) -> i32 {2}
}
fn call_foo_uint() -> i32 {
let mut x = Vec::new();
let y = x.foo();
x.push(0u32);
y
}
fn call_foo_int() -> i32 {
let mut x = Vec::new();
let y = x.foo();
x.push(0i32);
y
}
fn main() {
assert_eq!(call_foo_uint(), 1);
assert_eq!(call_foo_int(), 2);
}
|
// 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.
|
random_line_split
|
|
method-two-trait-defer-resolution-1.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.
// Test that we pick which version of `foo` to run based on the
// type that is (ultimately) inferred for `x`.
trait foo {
fn foo(&self) -> i32;
}
impl foo for Vec<u32> {
fn foo(&self) -> i32 {1}
}
impl foo for Vec<i32> {
fn foo(&self) -> i32 {2}
}
fn
|
() -> i32 {
let mut x = Vec::new();
let y = x.foo();
x.push(0u32);
y
}
fn call_foo_int() -> i32 {
let mut x = Vec::new();
let y = x.foo();
x.push(0i32);
y
}
fn main() {
assert_eq!(call_foo_uint(), 1);
assert_eq!(call_foo_int(), 2);
}
|
call_foo_uint
|
identifier_name
|
annotations.rs
|
//! Types and functions related to bindgen annotation comments.
//!
//! Users can add annotations in doc comments to types that they would like to
//! replace other types with, mark as opaque, etc. This module deals with all of
//! that stuff.
use clang;
/// What kind of accessor should we provide for a field?
#[derive(Copy, PartialEq, Clone, Debug)]
pub enum FieldAccessorKind {
/// No accessor.
None,
/// Plain accessor.
Regular,
/// Unsafe accessor.
Unsafe,
/// Immutable accessor.
Immutable,
}
/// Annotations for a given item, or a field.
#[derive(Clone, PartialEq, Debug)]
pub struct Annotations {
/// Whether this item is marked as opaque. Only applies to types.
opaque: bool,
/// Whether this item should be hidden from the output. Only applies to
/// types.
hide: bool,
/// Whether this type should be replaced by another. The name must be the
/// canonical name that that type would get.
use_instead_of: Option<String>,
/// Manually disable deriving copy/clone on this type. Only applies to
/// struct or union types.
disallow_copy: bool,
/// Whether fields should be marked as private or not. You can set this on
/// structs (it will apply to all the fields), or individual fields.
private_fields: Option<bool>,
/// The kind of accessor this field will have. Also can be applied to
/// structs so all the fields inside share it by default.
accessor_kind: Option<FieldAccessorKind>,
}
fn parse_accessor(s: &str) -> FieldAccessorKind {
match s {
"false" => FieldAccessorKind::None,
"unsafe" => FieldAccessorKind::Unsafe,
"immutable" => FieldAccessorKind::Immutable,
_ => FieldAccessorKind::Regular,
}
}
impl Default for Annotations {
fn default() -> Self {
Annotations {
opaque: false,
hide: false,
use_instead_of: None,
disallow_copy: false,
private_fields: None,
accessor_kind: None
}
}
}
impl Annotations {
/// Construct new annotations for the given cursor and its bindgen comments
/// (if any).
pub fn new(cursor: &clang::Cursor) -> Option<Annotations> {
let mut anno = Annotations::default();
let mut matched_one = false;
anno.parse(&cursor.comment(), &mut matched_one);
if matched_one {
Some(anno)
} else {
None
}
}
/// Should this type be hidden?
pub fn hide(&self) -> bool {
self.hide
}
/// Should this type be opaque?
pub fn opaque(&self) -> bool
|
/// For a given type, indicates the type it should replace.
///
/// For example, in the following code:
///
/// ```cpp
///
/// /** <div rustbindgen replaces="Bar"></div> */
/// struct Foo { int x; };
///
/// struct Bar { char foo; };
/// ```
///
/// the generated code would look something like:
///
/// ```
/// /** <div rustbindgen replaces="Bar"></div> */
/// struct Bar {
/// x: ::std::os::raw::c_int,
/// };
/// ```
///
/// That is, code for `Foo` is used to generate `Bar`.
pub fn use_instead_of(&self) -> Option<&str> {
self.use_instead_of.as_ref().map(|s| &**s)
}
/// Should we avoid implementing the `Copy` trait?
pub fn disallow_copy(&self) -> bool {
self.disallow_copy
}
/// Should the fields be private?
pub fn private_fields(&self) -> Option<bool> {
self.private_fields
}
/// What kind of accessors should we provide for this type's fields?
pub fn accessor_kind(&self) -> Option<FieldAccessorKind> {
self.accessor_kind
}
fn parse(&mut self, comment: &clang::Comment, matched: &mut bool) {
use clangll::CXComment_HTMLStartTag;
if comment.kind() == CXComment_HTMLStartTag &&
comment.get_tag_name() == "div" &&
comment.get_num_tag_attrs() > 1 &&
comment.get_tag_attr_name(0) == "rustbindgen" {
*matched = true;
for i in 0..comment.get_num_tag_attrs() {
let value = comment.get_tag_attr_value(i);
let name = comment.get_tag_attr_name(i);
match name.as_str() {
"opaque" => self.opaque = true,
"hide" => self.hide = true,
"nocopy" => self.disallow_copy = true,
"replaces" => self.use_instead_of = Some(value),
"private" => self.private_fields = Some(value!= "false"),
"accessor"
=> self.accessor_kind = Some(parse_accessor(&value)),
_ => {},
}
}
}
for i in 0..comment.num_children() {
self.parse(&comment.get_child(i), matched);
}
}
}
|
{
self.opaque
}
|
identifier_body
|
annotations.rs
|
//! Types and functions related to bindgen annotation comments.
//!
//! Users can add annotations in doc comments to types that they would like to
//! replace other types with, mark as opaque, etc. This module deals with all of
//! that stuff.
use clang;
/// What kind of accessor should we provide for a field?
#[derive(Copy, PartialEq, Clone, Debug)]
pub enum FieldAccessorKind {
/// No accessor.
None,
/// Plain accessor.
Regular,
/// Unsafe accessor.
Unsafe,
/// Immutable accessor.
Immutable,
}
/// Annotations for a given item, or a field.
#[derive(Clone, PartialEq, Debug)]
pub struct Annotations {
/// Whether this item is marked as opaque. Only applies to types.
opaque: bool,
/// Whether this item should be hidden from the output. Only applies to
/// types.
hide: bool,
/// Whether this type should be replaced by another. The name must be the
/// canonical name that that type would get.
use_instead_of: Option<String>,
/// Manually disable deriving copy/clone on this type. Only applies to
/// struct or union types.
disallow_copy: bool,
/// Whether fields should be marked as private or not. You can set this on
/// structs (it will apply to all the fields), or individual fields.
private_fields: Option<bool>,
/// The kind of accessor this field will have. Also can be applied to
/// structs so all the fields inside share it by default.
accessor_kind: Option<FieldAccessorKind>,
}
fn parse_accessor(s: &str) -> FieldAccessorKind {
match s {
"false" => FieldAccessorKind::None,
"unsafe" => FieldAccessorKind::Unsafe,
"immutable" => FieldAccessorKind::Immutable,
_ => FieldAccessorKind::Regular,
}
}
impl Default for Annotations {
fn default() -> Self {
Annotations {
opaque: false,
hide: false,
use_instead_of: None,
disallow_copy: false,
private_fields: None,
accessor_kind: None
}
}
}
impl Annotations {
/// Construct new annotations for the given cursor and its bindgen comments
/// (if any).
pub fn new(cursor: &clang::Cursor) -> Option<Annotations> {
let mut anno = Annotations::default();
let mut matched_one = false;
anno.parse(&cursor.comment(), &mut matched_one);
if matched_one {
Some(anno)
} else {
None
}
}
/// Should this type be hidden?
pub fn hide(&self) -> bool {
self.hide
}
/// Should this type be opaque?
pub fn opaque(&self) -> bool {
self.opaque
}
/// For a given type, indicates the type it should replace.
///
/// For example, in the following code:
///
/// ```cpp
///
/// /** <div rustbindgen replaces="Bar"></div> */
/// struct Foo { int x; };
|
/// ```
///
/// the generated code would look something like:
///
/// ```
/// /** <div rustbindgen replaces="Bar"></div> */
/// struct Bar {
/// x: ::std::os::raw::c_int,
/// };
/// ```
///
/// That is, code for `Foo` is used to generate `Bar`.
pub fn use_instead_of(&self) -> Option<&str> {
self.use_instead_of.as_ref().map(|s| &**s)
}
/// Should we avoid implementing the `Copy` trait?
pub fn disallow_copy(&self) -> bool {
self.disallow_copy
}
/// Should the fields be private?
pub fn private_fields(&self) -> Option<bool> {
self.private_fields
}
/// What kind of accessors should we provide for this type's fields?
pub fn accessor_kind(&self) -> Option<FieldAccessorKind> {
self.accessor_kind
}
fn parse(&mut self, comment: &clang::Comment, matched: &mut bool) {
use clangll::CXComment_HTMLStartTag;
if comment.kind() == CXComment_HTMLStartTag &&
comment.get_tag_name() == "div" &&
comment.get_num_tag_attrs() > 1 &&
comment.get_tag_attr_name(0) == "rustbindgen" {
*matched = true;
for i in 0..comment.get_num_tag_attrs() {
let value = comment.get_tag_attr_value(i);
let name = comment.get_tag_attr_name(i);
match name.as_str() {
"opaque" => self.opaque = true,
"hide" => self.hide = true,
"nocopy" => self.disallow_copy = true,
"replaces" => self.use_instead_of = Some(value),
"private" => self.private_fields = Some(value!= "false"),
"accessor"
=> self.accessor_kind = Some(parse_accessor(&value)),
_ => {},
}
}
}
for i in 0..comment.num_children() {
self.parse(&comment.get_child(i), matched);
}
}
}
|
///
/// struct Bar { char foo; };
|
random_line_split
|
annotations.rs
|
//! Types and functions related to bindgen annotation comments.
//!
//! Users can add annotations in doc comments to types that they would like to
//! replace other types with, mark as opaque, etc. This module deals with all of
//! that stuff.
use clang;
/// What kind of accessor should we provide for a field?
#[derive(Copy, PartialEq, Clone, Debug)]
pub enum FieldAccessorKind {
/// No accessor.
None,
/// Plain accessor.
Regular,
/// Unsafe accessor.
Unsafe,
/// Immutable accessor.
Immutable,
}
/// Annotations for a given item, or a field.
#[derive(Clone, PartialEq, Debug)]
pub struct Annotations {
/// Whether this item is marked as opaque. Only applies to types.
opaque: bool,
/// Whether this item should be hidden from the output. Only applies to
/// types.
hide: bool,
/// Whether this type should be replaced by another. The name must be the
/// canonical name that that type would get.
use_instead_of: Option<String>,
/// Manually disable deriving copy/clone on this type. Only applies to
/// struct or union types.
disallow_copy: bool,
/// Whether fields should be marked as private or not. You can set this on
/// structs (it will apply to all the fields), or individual fields.
private_fields: Option<bool>,
/// The kind of accessor this field will have. Also can be applied to
/// structs so all the fields inside share it by default.
accessor_kind: Option<FieldAccessorKind>,
}
fn parse_accessor(s: &str) -> FieldAccessorKind {
match s {
"false" => FieldAccessorKind::None,
"unsafe" => FieldAccessorKind::Unsafe,
"immutable" => FieldAccessorKind::Immutable,
_ => FieldAccessorKind::Regular,
}
}
impl Default for Annotations {
fn default() -> Self {
Annotations {
opaque: false,
hide: false,
use_instead_of: None,
disallow_copy: false,
private_fields: None,
accessor_kind: None
}
}
}
impl Annotations {
/// Construct new annotations for the given cursor and its bindgen comments
/// (if any).
pub fn new(cursor: &clang::Cursor) -> Option<Annotations> {
let mut anno = Annotations::default();
let mut matched_one = false;
anno.parse(&cursor.comment(), &mut matched_one);
if matched_one {
Some(anno)
} else {
None
}
}
/// Should this type be hidden?
pub fn hide(&self) -> bool {
self.hide
}
/// Should this type be opaque?
pub fn opaque(&self) -> bool {
self.opaque
}
/// For a given type, indicates the type it should replace.
///
/// For example, in the following code:
///
/// ```cpp
///
/// /** <div rustbindgen replaces="Bar"></div> */
/// struct Foo { int x; };
///
/// struct Bar { char foo; };
/// ```
///
/// the generated code would look something like:
///
/// ```
/// /** <div rustbindgen replaces="Bar"></div> */
/// struct Bar {
/// x: ::std::os::raw::c_int,
/// };
/// ```
///
/// That is, code for `Foo` is used to generate `Bar`.
pub fn use_instead_of(&self) -> Option<&str> {
self.use_instead_of.as_ref().map(|s| &**s)
}
/// Should we avoid implementing the `Copy` trait?
pub fn disallow_copy(&self) -> bool {
self.disallow_copy
}
/// Should the fields be private?
pub fn
|
(&self) -> Option<bool> {
self.private_fields
}
/// What kind of accessors should we provide for this type's fields?
pub fn accessor_kind(&self) -> Option<FieldAccessorKind> {
self.accessor_kind
}
fn parse(&mut self, comment: &clang::Comment, matched: &mut bool) {
use clangll::CXComment_HTMLStartTag;
if comment.kind() == CXComment_HTMLStartTag &&
comment.get_tag_name() == "div" &&
comment.get_num_tag_attrs() > 1 &&
comment.get_tag_attr_name(0) == "rustbindgen" {
*matched = true;
for i in 0..comment.get_num_tag_attrs() {
let value = comment.get_tag_attr_value(i);
let name = comment.get_tag_attr_name(i);
match name.as_str() {
"opaque" => self.opaque = true,
"hide" => self.hide = true,
"nocopy" => self.disallow_copy = true,
"replaces" => self.use_instead_of = Some(value),
"private" => self.private_fields = Some(value!= "false"),
"accessor"
=> self.accessor_kind = Some(parse_accessor(&value)),
_ => {},
}
}
}
for i in 0..comment.num_children() {
self.parse(&comment.get_child(i), matched);
}
}
}
|
private_fields
|
identifier_name
|
path_utils.rs
|
use crate::borrow_set::{BorrowData, BorrowSet, TwoPhaseActivation};
use crate::places_conflict;
use crate::AccessDepth;
use crate::BorrowIndex;
use crate::Upvar;
use rustc_data_structures::graph::dominators::Dominators;
use rustc_middle::mir::BorrowKind;
use rustc_middle::mir::{BasicBlock, Body, Field, Location, Place, PlaceRef, ProjectionElem};
use rustc_middle::ty::TyCtxt;
/// Returns `true` if the borrow represented by `kind` is
/// allowed to be split into separate Reservation and
/// Activation phases.
pub(super) fn allow_two_phase_borrow(kind: BorrowKind) -> bool {
kind.allows_two_phase_borrow()
}
/// Control for the path borrow checking code
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub(super) enum Control {
Continue,
Break,
}
/// Encapsulates the idea of iterating over every borrow that involves a particular path
pub(super) fn each_borrow_involving_path<'tcx, F, I, S>(
s: &mut S,
tcx: TyCtxt<'tcx>,
body: &Body<'tcx>,
_location: Location,
access_place: (AccessDepth, Place<'tcx>),
borrow_set: &BorrowSet<'tcx>,
candidates: I,
mut op: F,
) where
F: FnMut(&mut S, BorrowIndex, &BorrowData<'tcx>) -> Control,
I: Iterator<Item = BorrowIndex>,
|
debug!(
"each_borrow_involving_path: {:?} @ {:?} vs. {:?}/{:?}",
i, borrowed, place, access
);
let ctrl = op(s, i, borrowed);
if ctrl == Control::Break {
return;
}
}
}
}
pub(super) fn is_active<'tcx>(
dominators: &Dominators<BasicBlock>,
borrow_data: &BorrowData<'tcx>,
location: Location,
) -> bool {
debug!("is_active(borrow_data={:?}, location={:?})", borrow_data, location);
let activation_location = match borrow_data.activation_location {
// If this is not a 2-phase borrow, it is always active.
TwoPhaseActivation::NotTwoPhase => return true,
// And if the unique 2-phase use is not an activation, then it is *never* active.
TwoPhaseActivation::NotActivated => return false,
// Otherwise, we derive info from the activation point `loc`:
TwoPhaseActivation::ActivatedAt(loc) => loc,
};
// Otherwise, it is active for every location *except* in between
// the reservation and the activation:
//
// X
// /
// R <--+ Except for this
// / \ | diamond
// \ / |
// A <------+
// |
// Z
//
// Note that we assume that:
// - the reservation R dominates the activation A
// - the activation A post-dominates the reservation R (ignoring unwinding edges).
//
// This means that there can't be an edge that leaves A and
// comes back into that diamond unless it passes through R.
//
// Suboptimal: In some cases, this code walks the dominator
// tree twice when it only has to be walked once. I am
// lazy. -nmatsakis
// If dominated by the activation A, then it is active. The
// activation occurs upon entering the point A, so this is
// also true if location == activation_location.
if activation_location.dominates(location, dominators) {
return true;
}
// The reservation starts *on exiting* the reservation block,
// so check if the location is dominated by R.successor. If so,
// this point falls in between the reservation and location.
let reserve_location = borrow_data.reserve_location.successor_within_block();
if reserve_location.dominates(location, dominators) {
false
} else {
// Otherwise, this point is outside the diamond, so
// consider the borrow active. This could happen for
// example if the borrow remains active around a loop (in
// which case it would be active also for the point R,
// which would generate an error).
true
}
}
/// Determines if a given borrow is borrowing local data
/// This is called for all Yield expressions on movable generators
pub(super) fn borrow_of_local_data(place: Place<'_>) -> bool {
// Reborrow of already borrowed data is ignored
// Any errors will be caught on the initial borrow
!place.is_indirect()
}
/// If `place` is a field projection, and the field is being projected from a closure type,
/// then returns the index of the field being projected. Note that this closure will always
/// be `self` in the current MIR, because that is the only time we directly access the fields
/// of a closure type.
pub(crate) fn is_upvar_field_projection(
tcx: TyCtxt<'tcx>,
upvars: &[Upvar<'tcx>],
place_ref: PlaceRef<'tcx>,
body: &Body<'tcx>,
) -> Option<Field> {
let mut place_ref = place_ref;
let mut by_ref = false;
if let Some((place_base, ProjectionElem::Deref)) = place_ref.last_projection() {
place_ref = place_base;
by_ref = true;
}
match place_ref.last_projection() {
Some((place_base, ProjectionElem::Field(field, _ty))) => {
let base_ty = place_base.ty(body, tcx).ty;
if (base_ty.is_closure() || base_ty.is_generator())
&& (!by_ref || upvars[field.index()].by_ref)
{
Some(field)
} else {
None
}
}
_ => None,
}
}
|
{
let (access, place) = access_place;
// FIXME: analogous code in check_loans first maps `place` to
// its base_path.
// check for loan restricting path P being used. Accounts for
// borrows of P, P.a.b, etc.
for i in candidates {
let borrowed = &borrow_set[i];
if places_conflict::borrow_conflicts_with_place(
tcx,
body,
borrowed.borrowed_place,
borrowed.kind,
place.as_ref(),
access,
places_conflict::PlaceConflictBias::Overlap,
) {
|
identifier_body
|
path_utils.rs
|
use crate::borrow_set::{BorrowData, BorrowSet, TwoPhaseActivation};
use crate::places_conflict;
use crate::AccessDepth;
use crate::BorrowIndex;
use crate::Upvar;
use rustc_data_structures::graph::dominators::Dominators;
use rustc_middle::mir::BorrowKind;
use rustc_middle::mir::{BasicBlock, Body, Field, Location, Place, PlaceRef, ProjectionElem};
use rustc_middle::ty::TyCtxt;
/// Returns `true` if the borrow represented by `kind` is
/// allowed to be split into separate Reservation and
/// Activation phases.
pub(super) fn allow_two_phase_borrow(kind: BorrowKind) -> bool {
kind.allows_two_phase_borrow()
}
/// Control for the path borrow checking code
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub(super) enum Control {
Continue,
Break,
}
/// Encapsulates the idea of iterating over every borrow that involves a particular path
pub(super) fn each_borrow_involving_path<'tcx, F, I, S>(
s: &mut S,
tcx: TyCtxt<'tcx>,
body: &Body<'tcx>,
_location: Location,
access_place: (AccessDepth, Place<'tcx>),
borrow_set: &BorrowSet<'tcx>,
candidates: I,
mut op: F,
) where
F: FnMut(&mut S, BorrowIndex, &BorrowData<'tcx>) -> Control,
I: Iterator<Item = BorrowIndex>,
{
let (access, place) = access_place;
// FIXME: analogous code in check_loans first maps `place` to
// its base_path.
// check for loan restricting path P being used. Accounts for
// borrows of P, P.a.b, etc.
for i in candidates {
let borrowed = &borrow_set[i];
if places_conflict::borrow_conflicts_with_place(
tcx,
body,
borrowed.borrowed_place,
borrowed.kind,
place.as_ref(),
access,
places_conflict::PlaceConflictBias::Overlap,
) {
debug!(
"each_borrow_involving_path: {:?} @ {:?} vs. {:?}/{:?}",
i, borrowed, place, access
);
let ctrl = op(s, i, borrowed);
if ctrl == Control::Break {
return;
}
}
}
}
pub(super) fn
|
<'tcx>(
dominators: &Dominators<BasicBlock>,
borrow_data: &BorrowData<'tcx>,
location: Location,
) -> bool {
debug!("is_active(borrow_data={:?}, location={:?})", borrow_data, location);
let activation_location = match borrow_data.activation_location {
// If this is not a 2-phase borrow, it is always active.
TwoPhaseActivation::NotTwoPhase => return true,
// And if the unique 2-phase use is not an activation, then it is *never* active.
TwoPhaseActivation::NotActivated => return false,
// Otherwise, we derive info from the activation point `loc`:
TwoPhaseActivation::ActivatedAt(loc) => loc,
};
// Otherwise, it is active for every location *except* in between
// the reservation and the activation:
//
// X
// /
// R <--+ Except for this
// / \ | diamond
// \ / |
// A <------+
// |
// Z
//
// Note that we assume that:
// - the reservation R dominates the activation A
// - the activation A post-dominates the reservation R (ignoring unwinding edges).
//
// This means that there can't be an edge that leaves A and
// comes back into that diamond unless it passes through R.
//
// Suboptimal: In some cases, this code walks the dominator
// tree twice when it only has to be walked once. I am
// lazy. -nmatsakis
// If dominated by the activation A, then it is active. The
// activation occurs upon entering the point A, so this is
// also true if location == activation_location.
if activation_location.dominates(location, dominators) {
return true;
}
// The reservation starts *on exiting* the reservation block,
// so check if the location is dominated by R.successor. If so,
// this point falls in between the reservation and location.
let reserve_location = borrow_data.reserve_location.successor_within_block();
if reserve_location.dominates(location, dominators) {
false
} else {
// Otherwise, this point is outside the diamond, so
// consider the borrow active. This could happen for
// example if the borrow remains active around a loop (in
// which case it would be active also for the point R,
// which would generate an error).
true
}
}
/// Determines if a given borrow is borrowing local data
/// This is called for all Yield expressions on movable generators
pub(super) fn borrow_of_local_data(place: Place<'_>) -> bool {
// Reborrow of already borrowed data is ignored
// Any errors will be caught on the initial borrow
!place.is_indirect()
}
/// If `place` is a field projection, and the field is being projected from a closure type,
/// then returns the index of the field being projected. Note that this closure will always
/// be `self` in the current MIR, because that is the only time we directly access the fields
/// of a closure type.
pub(crate) fn is_upvar_field_projection(
tcx: TyCtxt<'tcx>,
upvars: &[Upvar<'tcx>],
place_ref: PlaceRef<'tcx>,
body: &Body<'tcx>,
) -> Option<Field> {
let mut place_ref = place_ref;
let mut by_ref = false;
if let Some((place_base, ProjectionElem::Deref)) = place_ref.last_projection() {
place_ref = place_base;
by_ref = true;
}
match place_ref.last_projection() {
Some((place_base, ProjectionElem::Field(field, _ty))) => {
let base_ty = place_base.ty(body, tcx).ty;
if (base_ty.is_closure() || base_ty.is_generator())
&& (!by_ref || upvars[field.index()].by_ref)
{
Some(field)
} else {
None
}
}
_ => None,
}
}
|
is_active
|
identifier_name
|
path_utils.rs
|
use crate::borrow_set::{BorrowData, BorrowSet, TwoPhaseActivation};
use crate::places_conflict;
use crate::AccessDepth;
use crate::BorrowIndex;
use crate::Upvar;
use rustc_data_structures::graph::dominators::Dominators;
use rustc_middle::mir::BorrowKind;
use rustc_middle::mir::{BasicBlock, Body, Field, Location, Place, PlaceRef, ProjectionElem};
use rustc_middle::ty::TyCtxt;
/// Returns `true` if the borrow represented by `kind` is
/// allowed to be split into separate Reservation and
/// Activation phases.
pub(super) fn allow_two_phase_borrow(kind: BorrowKind) -> bool {
kind.allows_two_phase_borrow()
}
/// Control for the path borrow checking code
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub(super) enum Control {
Continue,
Break,
}
/// Encapsulates the idea of iterating over every borrow that involves a particular path
pub(super) fn each_borrow_involving_path<'tcx, F, I, S>(
s: &mut S,
tcx: TyCtxt<'tcx>,
body: &Body<'tcx>,
_location: Location,
access_place: (AccessDepth, Place<'tcx>),
borrow_set: &BorrowSet<'tcx>,
candidates: I,
mut op: F,
) where
F: FnMut(&mut S, BorrowIndex, &BorrowData<'tcx>) -> Control,
I: Iterator<Item = BorrowIndex>,
{
let (access, place) = access_place;
// FIXME: analogous code in check_loans first maps `place` to
// its base_path.
// check for loan restricting path P being used. Accounts for
// borrows of P, P.a.b, etc.
for i in candidates {
let borrowed = &borrow_set[i];
if places_conflict::borrow_conflicts_with_place(
tcx,
body,
borrowed.borrowed_place,
borrowed.kind,
place.as_ref(),
access,
places_conflict::PlaceConflictBias::Overlap,
) {
debug!(
"each_borrow_involving_path: {:?} @ {:?} vs. {:?}/{:?}",
i, borrowed, place, access
);
let ctrl = op(s, i, borrowed);
if ctrl == Control::Break {
return;
}
}
}
}
pub(super) fn is_active<'tcx>(
dominators: &Dominators<BasicBlock>,
borrow_data: &BorrowData<'tcx>,
location: Location,
) -> bool {
debug!("is_active(borrow_data={:?}, location={:?})", borrow_data, location);
let activation_location = match borrow_data.activation_location {
// If this is not a 2-phase borrow, it is always active.
TwoPhaseActivation::NotTwoPhase => return true,
// And if the unique 2-phase use is not an activation, then it is *never* active.
TwoPhaseActivation::NotActivated => return false,
// Otherwise, we derive info from the activation point `loc`:
TwoPhaseActivation::ActivatedAt(loc) => loc,
};
// Otherwise, it is active for every location *except* in between
// the reservation and the activation:
//
// X
// /
// R <--+ Except for this
// / \ | diamond
// \ / |
// A <------+
// |
// Z
//
// Note that we assume that:
// - the reservation R dominates the activation A
// - the activation A post-dominates the reservation R (ignoring unwinding edges).
//
// This means that there can't be an edge that leaves A and
// comes back into that diamond unless it passes through R.
//
// Suboptimal: In some cases, this code walks the dominator
// tree twice when it only has to be walked once. I am
// lazy. -nmatsakis
// If dominated by the activation A, then it is active. The
// activation occurs upon entering the point A, so this is
// also true if location == activation_location.
if activation_location.dominates(location, dominators) {
return true;
}
// The reservation starts *on exiting* the reservation block,
// so check if the location is dominated by R.successor. If so,
// this point falls in between the reservation and location.
let reserve_location = borrow_data.reserve_location.successor_within_block();
if reserve_location.dominates(location, dominators) {
false
} else {
// Otherwise, this point is outside the diamond, so
// consider the borrow active. This could happen for
// example if the borrow remains active around a loop (in
// which case it would be active also for the point R,
// which would generate an error).
true
}
}
/// Determines if a given borrow is borrowing local data
/// This is called for all Yield expressions on movable generators
pub(super) fn borrow_of_local_data(place: Place<'_>) -> bool {
// Reborrow of already borrowed data is ignored
// Any errors will be caught on the initial borrow
!place.is_indirect()
}
/// If `place` is a field projection, and the field is being projected from a closure type,
/// then returns the index of the field being projected. Note that this closure will always
/// be `self` in the current MIR, because that is the only time we directly access the fields
/// of a closure type.
pub(crate) fn is_upvar_field_projection(
|
) -> Option<Field> {
let mut place_ref = place_ref;
let mut by_ref = false;
if let Some((place_base, ProjectionElem::Deref)) = place_ref.last_projection() {
place_ref = place_base;
by_ref = true;
}
match place_ref.last_projection() {
Some((place_base, ProjectionElem::Field(field, _ty))) => {
let base_ty = place_base.ty(body, tcx).ty;
if (base_ty.is_closure() || base_ty.is_generator())
&& (!by_ref || upvars[field.index()].by_ref)
{
Some(field)
} else {
None
}
}
_ => None,
}
}
|
tcx: TyCtxt<'tcx>,
upvars: &[Upvar<'tcx>],
place_ref: PlaceRef<'tcx>,
body: &Body<'tcx>,
|
random_line_split
|
trait-bounds-in-arc.rs
|
// xfail-pretty
// 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.
// Tests that a heterogeneous list of existential types can be put inside an Arc
// and shared between tasks as long as all types fulfill Freeze+Send.
// xfail-fast
extern mod extra;
use extra::arc;
use std::comm;
use std::task;
trait Pet {
fn name(&self, blk: |&str|);
fn num_legs(&self) -> uint;
fn of_good_pedigree(&self) -> bool;
}
struct Catte {
num_whiskers: uint,
name: ~str,
}
struct Dogge {
bark_decibels: uint,
tricks_known: uint,
name: ~str,
}
struct Goldfyshe {
swim_speed: uint,
name: ~str,
}
impl Pet for Catte {
fn name(&self, blk: |&str|) { blk(self.name) }
fn num_legs(&self) -> uint { 4 }
fn of_good_pedigree(&self) -> bool { self.num_whiskers >= 4 }
}
impl Pet for Dogge {
fn name(&self, blk: |&str|) { blk(self.name) }
fn num_legs(&self) -> uint { 4 }
fn of_good_pedigree(&self) -> bool {
self.bark_decibels < 70 || self.tricks_known > 20
}
}
impl Pet for Goldfyshe {
fn name(&self, blk: |&str|) { blk(self.name) }
fn num_legs(&self) -> uint { 0 }
fn of_good_pedigree(&self) -> bool { self.swim_speed >= 500 }
}
fn main() {
let catte = Catte { num_whiskers: 7, name: ~"alonzo_church" };
let dogge1 = Dogge { bark_decibels: 100, tricks_known: 42, name: ~"alan_turing" };
let dogge2 = Dogge { bark_decibels: 55, tricks_known: 11, name: ~"albert_einstein" };
let fishe = Goldfyshe { swim_speed: 998, name: ~"alec_guinness" };
let arc = arc::Arc::new(~[~catte as ~Pet:Freeze+Send,
~dogge1 as ~Pet:Freeze+Send,
~fishe as ~Pet:Freeze+Send,
~dogge2 as ~Pet:Freeze+Send]);
let (p1,c1) = comm::stream();
let arc1 = arc.clone();
do task::spawn { check_legs(arc1); c1.send(()); }
|
let (p2,c2) = comm::stream();
let arc2 = arc.clone();
do task::spawn { check_names(arc2); c2.send(()); }
let (p3,c3) = comm::stream();
let arc3 = arc.clone();
do task::spawn { check_pedigree(arc3); c3.send(()); }
p1.recv();
p2.recv();
p3.recv();
}
fn check_legs(arc: arc::Arc<~[~Pet:Freeze+Send]>) {
let mut legs = 0;
for pet in arc.get().iter() {
legs += pet.num_legs();
}
assert!(legs == 12);
}
fn check_names(arc: arc::Arc<~[~Pet:Freeze+Send]>) {
for pet in arc.get().iter() {
pet.name(|name| {
assert!(name[0] == 'a' as u8 && name[1] == 'l' as u8);
})
}
}
fn check_pedigree(arc: arc::Arc<~[~Pet:Freeze+Send]>) {
for pet in arc.get().iter() {
assert!(pet.of_good_pedigree());
}
}
|
random_line_split
|
|
trait-bounds-in-arc.rs
|
// xfail-pretty
// 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.
// Tests that a heterogeneous list of existential types can be put inside an Arc
// and shared between tasks as long as all types fulfill Freeze+Send.
// xfail-fast
extern mod extra;
use extra::arc;
use std::comm;
use std::task;
trait Pet {
fn name(&self, blk: |&str|);
fn num_legs(&self) -> uint;
fn of_good_pedigree(&self) -> bool;
}
struct
|
{
num_whiskers: uint,
name: ~str,
}
struct Dogge {
bark_decibels: uint,
tricks_known: uint,
name: ~str,
}
struct Goldfyshe {
swim_speed: uint,
name: ~str,
}
impl Pet for Catte {
fn name(&self, blk: |&str|) { blk(self.name) }
fn num_legs(&self) -> uint { 4 }
fn of_good_pedigree(&self) -> bool { self.num_whiskers >= 4 }
}
impl Pet for Dogge {
fn name(&self, blk: |&str|) { blk(self.name) }
fn num_legs(&self) -> uint { 4 }
fn of_good_pedigree(&self) -> bool {
self.bark_decibels < 70 || self.tricks_known > 20
}
}
impl Pet for Goldfyshe {
fn name(&self, blk: |&str|) { blk(self.name) }
fn num_legs(&self) -> uint { 0 }
fn of_good_pedigree(&self) -> bool { self.swim_speed >= 500 }
}
fn main() {
let catte = Catte { num_whiskers: 7, name: ~"alonzo_church" };
let dogge1 = Dogge { bark_decibels: 100, tricks_known: 42, name: ~"alan_turing" };
let dogge2 = Dogge { bark_decibels: 55, tricks_known: 11, name: ~"albert_einstein" };
let fishe = Goldfyshe { swim_speed: 998, name: ~"alec_guinness" };
let arc = arc::Arc::new(~[~catte as ~Pet:Freeze+Send,
~dogge1 as ~Pet:Freeze+Send,
~fishe as ~Pet:Freeze+Send,
~dogge2 as ~Pet:Freeze+Send]);
let (p1,c1) = comm::stream();
let arc1 = arc.clone();
do task::spawn { check_legs(arc1); c1.send(()); }
let (p2,c2) = comm::stream();
let arc2 = arc.clone();
do task::spawn { check_names(arc2); c2.send(()); }
let (p3,c3) = comm::stream();
let arc3 = arc.clone();
do task::spawn { check_pedigree(arc3); c3.send(()); }
p1.recv();
p2.recv();
p3.recv();
}
fn check_legs(arc: arc::Arc<~[~Pet:Freeze+Send]>) {
let mut legs = 0;
for pet in arc.get().iter() {
legs += pet.num_legs();
}
assert!(legs == 12);
}
fn check_names(arc: arc::Arc<~[~Pet:Freeze+Send]>) {
for pet in arc.get().iter() {
pet.name(|name| {
assert!(name[0] == 'a' as u8 && name[1] == 'l' as u8);
})
}
}
fn check_pedigree(arc: arc::Arc<~[~Pet:Freeze+Send]>) {
for pet in arc.get().iter() {
assert!(pet.of_good_pedigree());
}
}
|
Catte
|
identifier_name
|
trait-bounds-in-arc.rs
|
// xfail-pretty
// 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.
// Tests that a heterogeneous list of existential types can be put inside an Arc
// and shared between tasks as long as all types fulfill Freeze+Send.
// xfail-fast
extern mod extra;
use extra::arc;
use std::comm;
use std::task;
trait Pet {
fn name(&self, blk: |&str|);
fn num_legs(&self) -> uint;
fn of_good_pedigree(&self) -> bool;
}
struct Catte {
num_whiskers: uint,
name: ~str,
}
struct Dogge {
bark_decibels: uint,
tricks_known: uint,
name: ~str,
}
struct Goldfyshe {
swim_speed: uint,
name: ~str,
}
impl Pet for Catte {
fn name(&self, blk: |&str|) { blk(self.name) }
fn num_legs(&self) -> uint { 4 }
fn of_good_pedigree(&self) -> bool { self.num_whiskers >= 4 }
}
impl Pet for Dogge {
fn name(&self, blk: |&str|) { blk(self.name) }
fn num_legs(&self) -> uint { 4 }
fn of_good_pedigree(&self) -> bool {
self.bark_decibels < 70 || self.tricks_known > 20
}
}
impl Pet for Goldfyshe {
fn name(&self, blk: |&str|) { blk(self.name) }
fn num_legs(&self) -> uint { 0 }
fn of_good_pedigree(&self) -> bool { self.swim_speed >= 500 }
}
fn main() {
let catte = Catte { num_whiskers: 7, name: ~"alonzo_church" };
let dogge1 = Dogge { bark_decibels: 100, tricks_known: 42, name: ~"alan_turing" };
let dogge2 = Dogge { bark_decibels: 55, tricks_known: 11, name: ~"albert_einstein" };
let fishe = Goldfyshe { swim_speed: 998, name: ~"alec_guinness" };
let arc = arc::Arc::new(~[~catte as ~Pet:Freeze+Send,
~dogge1 as ~Pet:Freeze+Send,
~fishe as ~Pet:Freeze+Send,
~dogge2 as ~Pet:Freeze+Send]);
let (p1,c1) = comm::stream();
let arc1 = arc.clone();
do task::spawn { check_legs(arc1); c1.send(()); }
let (p2,c2) = comm::stream();
let arc2 = arc.clone();
do task::spawn { check_names(arc2); c2.send(()); }
let (p3,c3) = comm::stream();
let arc3 = arc.clone();
do task::spawn { check_pedigree(arc3); c3.send(()); }
p1.recv();
p2.recv();
p3.recv();
}
fn check_legs(arc: arc::Arc<~[~Pet:Freeze+Send]>)
|
fn check_names(arc: arc::Arc<~[~Pet:Freeze+Send]>) {
for pet in arc.get().iter() {
pet.name(|name| {
assert!(name[0] == 'a' as u8 && name[1] == 'l' as u8);
})
}
}
fn check_pedigree(arc: arc::Arc<~[~Pet:Freeze+Send]>) {
for pet in arc.get().iter() {
assert!(pet.of_good_pedigree());
}
}
|
{
let mut legs = 0;
for pet in arc.get().iter() {
legs += pet.num_legs();
}
assert!(legs == 12);
}
|
identifier_body
|
TestNextafter.rs
|
/*
* Copyright (C) 2014 The Android Open Source Project
*
* 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.
*/
#pragma version(1)
#pragma rs java_package_name(android.renderscript.cts)
// Don't edit this file! It is auto-generated by frameworks/rs/api/gen_runtime.
|
}
float2 __attribute__((kernel)) testNextafterFloat2Float2Float2(float2 inX, unsigned int x) {
float2 inY = rsGetElementAt_float2(gAllocInY, x);
return nextafter(inX, inY);
}
float3 __attribute__((kernel)) testNextafterFloat3Float3Float3(float3 inX, unsigned int x) {
float3 inY = rsGetElementAt_float3(gAllocInY, x);
return nextafter(inX, inY);
}
float4 __attribute__((kernel)) testNextafterFloat4Float4Float4(float4 inX, unsigned int x) {
float4 inY = rsGetElementAt_float4(gAllocInY, x);
return nextafter(inX, inY);
}
|
rs_allocation gAllocInY;
float __attribute__((kernel)) testNextafterFloatFloatFloat(float inX, unsigned int x) {
float inY = rsGetElementAt_float(gAllocInY, x);
return nextafter(inX, inY);
|
random_line_split
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.