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 |
---|---|---|---|---|
intrinsic-raw_eq-const.rs | // run-pass
#![feature(core_intrinsics)]
#![feature(const_intrinsic_raw_eq)]
#![deny(const_err)]
pub fn | () {
use std::intrinsics::raw_eq;
const RAW_EQ_I32_TRUE: bool = unsafe { raw_eq(&42_i32, &42) };
assert!(RAW_EQ_I32_TRUE);
const RAW_EQ_I32_FALSE: bool = unsafe { raw_eq(&4_i32, &2) };
assert!(!RAW_EQ_I32_FALSE);
const RAW_EQ_CHAR_TRUE: bool = unsafe { raw_eq(&'a', &'a') };
assert!(RAW_EQ_CHAR_TRUE);
const RAW_EQ_CHAR_FALSE: bool = unsafe { raw_eq(&'a', &'A') };
assert!(!RAW_EQ_CHAR_FALSE);
const RAW_EQ_ARRAY_TRUE: bool = unsafe { raw_eq(&[13_u8, 42], &[13, 42]) };
assert!(RAW_EQ_ARRAY_TRUE);
const RAW_EQ_ARRAY_FALSE: bool = unsafe { raw_eq(&[13_u8, 42], &[42, 13]) };
assert!(!RAW_EQ_ARRAY_FALSE);
}
| main | identifier_name |
intrinsic-raw_eq-const.rs | // run-pass
#![feature(core_intrinsics)]
#![feature(const_intrinsic_raw_eq)]
#![deny(const_err)]
pub fn main() | }
| {
use std::intrinsics::raw_eq;
const RAW_EQ_I32_TRUE: bool = unsafe { raw_eq(&42_i32, &42) };
assert!(RAW_EQ_I32_TRUE);
const RAW_EQ_I32_FALSE: bool = unsafe { raw_eq(&4_i32, &2) };
assert!(!RAW_EQ_I32_FALSE);
const RAW_EQ_CHAR_TRUE: bool = unsafe { raw_eq(&'a', &'a') };
assert!(RAW_EQ_CHAR_TRUE);
const RAW_EQ_CHAR_FALSE: bool = unsafe { raw_eq(&'a', &'A') };
assert!(!RAW_EQ_CHAR_FALSE);
const RAW_EQ_ARRAY_TRUE: bool = unsafe { raw_eq(&[13_u8, 42], &[13, 42]) };
assert!(RAW_EQ_ARRAY_TRUE);
const RAW_EQ_ARRAY_FALSE: bool = unsafe { raw_eq(&[13_u8, 42], &[42, 13]) };
assert!(!RAW_EQ_ARRAY_FALSE); | identifier_body |
intrinsic-raw_eq-const.rs | // run-pass
#![feature(core_intrinsics)]
#![feature(const_intrinsic_raw_eq)]
#![deny(const_err)]
pub fn main() {
use std::intrinsics::raw_eq;
const RAW_EQ_I32_TRUE: bool = unsafe { raw_eq(&42_i32, &42) };
assert!(RAW_EQ_I32_TRUE);
const RAW_EQ_I32_FALSE: bool = unsafe { raw_eq(&4_i32, &2) };
assert!(!RAW_EQ_I32_FALSE); | const RAW_EQ_CHAR_FALSE: bool = unsafe { raw_eq(&'a', &'A') };
assert!(!RAW_EQ_CHAR_FALSE);
const RAW_EQ_ARRAY_TRUE: bool = unsafe { raw_eq(&[13_u8, 42], &[13, 42]) };
assert!(RAW_EQ_ARRAY_TRUE);
const RAW_EQ_ARRAY_FALSE: bool = unsafe { raw_eq(&[13_u8, 42], &[42, 13]) };
assert!(!RAW_EQ_ARRAY_FALSE);
} |
const RAW_EQ_CHAR_TRUE: bool = unsafe { raw_eq(&'a', &'a') };
assert!(RAW_EQ_CHAR_TRUE);
| random_line_split |
main.rs | extern crate parolrs;
extern crate sodiumoxide;
use parolrs::core::{Parols, Parol};
use parolrs::utils::{load_database, save_database};
use sodiumoxide::crypto::secretbox::gen_nonce;
// in 9.90user 3.55system 0:14.92elapsed 90%CPU :)
fn main() {
let mut parols = Parols::new();
for i in 0.. 100_000 {
let parol = Parol::new_with_arguments( | "Ogromny",
"admin",
"blabla",
);
parols.push(parol);
}
for i in 0.. 100 {
let nonce = gen_nonce();
save_database(&parols, &nonce, "admin").unwrap();
if i == 99 {
println!("load_database(\"admin\").ok().unwrap() = {:#?}", load_database("admin").ok().unwrap());
} else {
load_database("admin").ok().unwrap();
}
}
} | &format!("tox{}", i), | random_line_split |
main.rs | extern crate parolrs;
extern crate sodiumoxide;
use parolrs::core::{Parols, Parol};
use parolrs::utils::{load_database, save_database};
use sodiumoxide::crypto::secretbox::gen_nonce;
// in 9.90user 3.55system 0:14.92elapsed 90%CPU :)
fn | () {
let mut parols = Parols::new();
for i in 0.. 100_000 {
let parol = Parol::new_with_arguments(
&format!("tox{}", i),
"Ogromny",
"admin",
"blabla",
);
parols.push(parol);
}
for i in 0.. 100 {
let nonce = gen_nonce();
save_database(&parols, &nonce, "admin").unwrap();
if i == 99 {
println!("load_database(\"admin\").ok().unwrap() = {:#?}", load_database("admin").ok().unwrap());
} else {
load_database("admin").ok().unwrap();
}
}
}
| main | identifier_name |
main.rs | extern crate parolrs;
extern crate sodiumoxide;
use parolrs::core::{Parols, Parol};
use parolrs::utils::{load_database, save_database};
use sodiumoxide::crypto::secretbox::gen_nonce;
// in 9.90user 3.55system 0:14.92elapsed 90%CPU :)
fn main() {
let mut parols = Parols::new();
for i in 0.. 100_000 {
let parol = Parol::new_with_arguments(
&format!("tox{}", i),
"Ogromny",
"admin",
"blabla",
);
parols.push(parol);
}
for i in 0.. 100 {
let nonce = gen_nonce();
save_database(&parols, &nonce, "admin").unwrap();
if i == 99 {
println!("load_database(\"admin\").ok().unwrap() = {:#?}", load_database("admin").ok().unwrap());
} else |
}
}
| {
load_database("admin").ok().unwrap();
} | conditional_block |
main.rs | extern crate parolrs;
extern crate sodiumoxide;
use parolrs::core::{Parols, Parol};
use parolrs::utils::{load_database, save_database};
use sodiumoxide::crypto::secretbox::gen_nonce;
// in 9.90user 3.55system 0:14.92elapsed 90%CPU :)
fn main() | }
}
| {
let mut parols = Parols::new();
for i in 0 .. 100_000 {
let parol = Parol::new_with_arguments(
&format!("tox{}", i),
"Ogromny",
"admin",
"blabla",
);
parols.push(parol);
}
for i in 0 .. 100 {
let nonce = gen_nonce();
save_database(&parols, &nonce, "admin").unwrap();
if i == 99 {
println!("load_database(\"admin\").ok().unwrap() = {:#?}", load_database("admin").ok().unwrap());
} else {
load_database("admin").ok().unwrap();
} | identifier_body |
rec-align-u64.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.
// xfail-fast: check-fast screws up repr paths
// Issue #2303
use std::sys;
mod rusti {
extern "rust-intrinsic" {
pub fn pref_align_of<T>() -> uint;
pub fn min_align_of<T>() -> uint;
}
}
// This is the type with the questionable alignment
struct Inner {
c64: u64
}
// This is the type that contains the type with the
// questionable alignment, for testing
struct Outer {
c8: u8,
t: Inner
}
#[cfg(target_os = "linux")]
#[cfg(target_os = "macos")]
#[cfg(target_os = "freebsd")]
mod m {
#[cfg(target_arch = "x86")]
pub mod m {
pub fn align() -> uint { 4u }
pub fn | () -> uint { 12u }
}
#[cfg(target_arch = "x86_64")]
pub mod m {
pub fn align() -> uint { 8u }
pub fn size() -> uint { 16u }
}
}
#[cfg(target_os = "win32")]
mod m {
#[cfg(target_arch = "x86")]
pub mod m {
pub fn align() -> uint { 8u }
pub fn size() -> uint { 16u }
}
}
#[cfg(target_os = "android")]
mod m {
#[cfg(target_arch = "arm")]
pub mod m {
pub fn align() -> uint { 8u }
pub fn size() -> uint { 16u }
}
}
pub fn main() {
unsafe {
let x = Outer {c8: 22u8, t: Inner {c64: 44u64}};
// Send it through the shape code
let y = format!("{:?}", x);
info2!("align inner = {}", rusti::min_align_of::<Inner>());
info2!("size outer = {}", sys::size_of::<Outer>());
info2!("y = {}", y);
// per clang/gcc the alignment of `Inner` is 4 on x86.
assert_eq!(rusti::min_align_of::<Inner>(), m::m::align());
// per clang/gcc the size of `Outer` should be 12
// because `Inner`s alignment was 4.
assert_eq!(sys::size_of::<Outer>(), m::m::size());
assert_eq!(y, ~"Outer{c8: 22u8, t: Inner{c64: 44u64}}");
}
}
| size | identifier_name |
rec-align-u64.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.
// xfail-fast: check-fast screws up repr paths
// Issue #2303
use std::sys;
mod rusti {
extern "rust-intrinsic" {
pub fn pref_align_of<T>() -> uint;
pub fn min_align_of<T>() -> uint;
}
}
// This is the type with the questionable alignment
struct Inner {
c64: u64
}
// This is the type that contains the type with the
// questionable alignment, for testing
struct Outer {
c8: u8,
t: Inner
}
#[cfg(target_os = "linux")]
#[cfg(target_os = "macos")]
#[cfg(target_os = "freebsd")]
mod m {
#[cfg(target_arch = "x86")]
pub mod m {
pub fn align() -> uint |
pub fn size() -> uint { 12u }
}
#[cfg(target_arch = "x86_64")]
pub mod m {
pub fn align() -> uint { 8u }
pub fn size() -> uint { 16u }
}
}
#[cfg(target_os = "win32")]
mod m {
#[cfg(target_arch = "x86")]
pub mod m {
pub fn align() -> uint { 8u }
pub fn size() -> uint { 16u }
}
}
#[cfg(target_os = "android")]
mod m {
#[cfg(target_arch = "arm")]
pub mod m {
pub fn align() -> uint { 8u }
pub fn size() -> uint { 16u }
}
}
pub fn main() {
unsafe {
let x = Outer {c8: 22u8, t: Inner {c64: 44u64}};
// Send it through the shape code
let y = format!("{:?}", x);
info2!("align inner = {}", rusti::min_align_of::<Inner>());
info2!("size outer = {}", sys::size_of::<Outer>());
info2!("y = {}", y);
// per clang/gcc the alignment of `Inner` is 4 on x86.
assert_eq!(rusti::min_align_of::<Inner>(), m::m::align());
// per clang/gcc the size of `Outer` should be 12
// because `Inner`s alignment was 4.
assert_eq!(sys::size_of::<Outer>(), m::m::size());
assert_eq!(y, ~"Outer{c8: 22u8, t: Inner{c64: 44u64}}");
}
}
| { 4u } | identifier_body |
rec-align-u64.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.
// | // option. This file may not be copied, modified, or distributed
// except according to those terms.
// xfail-fast: check-fast screws up repr paths
// Issue #2303
use std::sys;
mod rusti {
extern "rust-intrinsic" {
pub fn pref_align_of<T>() -> uint;
pub fn min_align_of<T>() -> uint;
}
}
// This is the type with the questionable alignment
struct Inner {
c64: u64
}
// This is the type that contains the type with the
// questionable alignment, for testing
struct Outer {
c8: u8,
t: Inner
}
#[cfg(target_os = "linux")]
#[cfg(target_os = "macos")]
#[cfg(target_os = "freebsd")]
mod m {
#[cfg(target_arch = "x86")]
pub mod m {
pub fn align() -> uint { 4u }
pub fn size() -> uint { 12u }
}
#[cfg(target_arch = "x86_64")]
pub mod m {
pub fn align() -> uint { 8u }
pub fn size() -> uint { 16u }
}
}
#[cfg(target_os = "win32")]
mod m {
#[cfg(target_arch = "x86")]
pub mod m {
pub fn align() -> uint { 8u }
pub fn size() -> uint { 16u }
}
}
#[cfg(target_os = "android")]
mod m {
#[cfg(target_arch = "arm")]
pub mod m {
pub fn align() -> uint { 8u }
pub fn size() -> uint { 16u }
}
}
pub fn main() {
unsafe {
let x = Outer {c8: 22u8, t: Inner {c64: 44u64}};
// Send it through the shape code
let y = format!("{:?}", x);
info2!("align inner = {}", rusti::min_align_of::<Inner>());
info2!("size outer = {}", sys::size_of::<Outer>());
info2!("y = {}", y);
// per clang/gcc the alignment of `Inner` is 4 on x86.
assert_eq!(rusti::min_align_of::<Inner>(), m::m::align());
// per clang/gcc the size of `Outer` should be 12
// because `Inner`s alignment was 4.
assert_eq!(sys::size_of::<Outer>(), m::m::size());
assert_eq!(y, ~"Outer{c8: 22u8, t: Inner{c64: 44u64}}");
}
} | // 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 | random_line_split |
issue-7013.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::rc::RcMut;
trait Foo
{
fn set(&mut self, v: RcMut<A>);
}
struct B
{
v: Option<RcMut<A>>
}
| }
}
struct A
{
v: ~Foo,
}
fn main()
{
let a = A {v: ~B{v: None} as ~Foo}; //~ ERROR cannot pack type `~B`, which does not fulfill `Send`
let v = RcMut::new(a); //~ ERROR instantiating a type parameter with an incompatible type
let w = v.clone();
v.with_mut_borrow(|p| {p.v.set(w.clone());})
} | impl Foo for B
{
fn set(&mut self, v: RcMut<A>)
{
self.v = Some(v); | random_line_split |
issue-7013.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::rc::RcMut;
trait Foo
{
fn set(&mut self, v: RcMut<A>);
}
struct B
{
v: Option<RcMut<A>>
}
impl Foo for B
{
fn set(&mut self, v: RcMut<A>)
{
self.v = Some(v);
}
}
struct A
{
v: ~Foo,
}
fn | ()
{
let a = A {v: ~B{v: None} as ~Foo}; //~ ERROR cannot pack type `~B`, which does not fulfill `Send`
let v = RcMut::new(a); //~ ERROR instantiating a type parameter with an incompatible type
let w = v.clone();
v.with_mut_borrow(|p| {p.v.set(w.clone());})
}
| main | identifier_name |
mut_ref.rs |
// Compiler:
//
// Run-time:
// stdout: 2
// 7
// 6
// 11
#![allow(unused_attributes)]
#![feature(auto_traits, lang_items, no_core, start, intrinsics, track_caller)]
#![no_std]
#![no_core]
/*
* Core
*/
// Because we don't have core yet.
#[lang = "sized"]
pub trait Sized {}
#[lang = "copy"]
trait Copy {
}
impl Copy for isize {}
impl Copy for *mut i32 {}
impl Copy for usize {}
impl Copy for u8 {}
impl Copy for i8 {}
impl Copy for i32 {}
#[lang = "receiver"]
trait Receiver {
}
#[lang = "freeze"]
pub(crate) unsafe auto trait Freeze {}
#[lang = "panic_location"]
struct PanicLocation {
file: &'static str,
line: u32,
column: u32,
}
mod libc {
#[link(name = "c")]
extern "C" {
pub fn puts(s: *const u8) -> i32;
pub fn fflush(stream: *mut i32) -> i32;
pub fn printf(format: *const i8,...) -> i32;
pub static STDOUT: *mut i32;
}
}
mod intrinsics {
extern "rust-intrinsic" {
pub fn abort() ->!;
}
}
#[lang = "panic"]
#[track_caller]
#[no_mangle]
pub fn panic(_msg: &str) ->! |
#[lang = "add"]
trait Add<RHS = Self> {
type Output;
fn add(self, rhs: RHS) -> Self::Output;
}
impl Add for u8 {
type Output = Self;
fn add(self, rhs: Self) -> Self {
self + rhs
}
}
impl Add for i8 {
type Output = Self;
fn add(self, rhs: Self) -> Self {
self + rhs
}
}
impl Add for i32 {
type Output = Self;
fn add(self, rhs: Self) -> Self {
self + rhs
}
}
impl Add for usize {
type Output = Self;
fn add(self, rhs: Self) -> Self {
self + rhs
}
}
impl Add for isize {
type Output = Self;
fn add(self, rhs: Self) -> Self {
self + rhs
}
}
/*
* Code
*/
struct Test {
field: isize,
}
fn test(num: isize) -> Test {
Test {
field: num + 1,
}
}
fn update_num(num: &mut isize) {
*num = *num + 5;
}
#[start]
fn main(mut argc: isize, _argv: *const *const u8) -> isize {
let mut test = test(argc);
unsafe {
libc::printf(b"%ld\n\0" as *const u8 as *const i8, test.field);
}
update_num(&mut test.field);
unsafe {
libc::printf(b"%ld\n\0" as *const u8 as *const i8, test.field);
}
update_num(&mut argc);
unsafe {
libc::printf(b"%ld\n\0" as *const u8 as *const i8, argc);
}
let refe = &mut argc;
*refe = *refe + 5;
unsafe {
libc::printf(b"%ld\n\0" as *const u8 as *const i8, argc);
}
0
}
| {
unsafe {
libc::puts("Panicking\0" as *const str as *const u8);
libc::fflush(libc::STDOUT);
intrinsics::abort();
}
} | identifier_body |
mut_ref.rs | // Compiler:
//
// Run-time:
// stdout: 2
// 7
// 6
// 11
#![allow(unused_attributes)]
#![feature(auto_traits, lang_items, no_core, start, intrinsics, track_caller)]
#![no_std]
#![no_core]
/*
* Core
*/
// Because we don't have core yet.
#[lang = "sized"]
pub trait Sized {}
| #[lang = "copy"]
trait Copy {
}
impl Copy for isize {}
impl Copy for *mut i32 {}
impl Copy for usize {}
impl Copy for u8 {}
impl Copy for i8 {}
impl Copy for i32 {}
#[lang = "receiver"]
trait Receiver {
}
#[lang = "freeze"]
pub(crate) unsafe auto trait Freeze {}
#[lang = "panic_location"]
struct PanicLocation {
file: &'static str,
line: u32,
column: u32,
}
mod libc {
#[link(name = "c")]
extern "C" {
pub fn puts(s: *const u8) -> i32;
pub fn fflush(stream: *mut i32) -> i32;
pub fn printf(format: *const i8,...) -> i32;
pub static STDOUT: *mut i32;
}
}
mod intrinsics {
extern "rust-intrinsic" {
pub fn abort() ->!;
}
}
#[lang = "panic"]
#[track_caller]
#[no_mangle]
pub fn panic(_msg: &str) ->! {
unsafe {
libc::puts("Panicking\0" as *const str as *const u8);
libc::fflush(libc::STDOUT);
intrinsics::abort();
}
}
#[lang = "add"]
trait Add<RHS = Self> {
type Output;
fn add(self, rhs: RHS) -> Self::Output;
}
impl Add for u8 {
type Output = Self;
fn add(self, rhs: Self) -> Self {
self + rhs
}
}
impl Add for i8 {
type Output = Self;
fn add(self, rhs: Self) -> Self {
self + rhs
}
}
impl Add for i32 {
type Output = Self;
fn add(self, rhs: Self) -> Self {
self + rhs
}
}
impl Add for usize {
type Output = Self;
fn add(self, rhs: Self) -> Self {
self + rhs
}
}
impl Add for isize {
type Output = Self;
fn add(self, rhs: Self) -> Self {
self + rhs
}
}
/*
* Code
*/
struct Test {
field: isize,
}
fn test(num: isize) -> Test {
Test {
field: num + 1,
}
}
fn update_num(num: &mut isize) {
*num = *num + 5;
}
#[start]
fn main(mut argc: isize, _argv: *const *const u8) -> isize {
let mut test = test(argc);
unsafe {
libc::printf(b"%ld\n\0" as *const u8 as *const i8, test.field);
}
update_num(&mut test.field);
unsafe {
libc::printf(b"%ld\n\0" as *const u8 as *const i8, test.field);
}
update_num(&mut argc);
unsafe {
libc::printf(b"%ld\n\0" as *const u8 as *const i8, argc);
}
let refe = &mut argc;
*refe = *refe + 5;
unsafe {
libc::printf(b"%ld\n\0" as *const u8 as *const i8, argc);
}
0
} | random_line_split |
|
mut_ref.rs |
// Compiler:
//
// Run-time:
// stdout: 2
// 7
// 6
// 11
#![allow(unused_attributes)]
#![feature(auto_traits, lang_items, no_core, start, intrinsics, track_caller)]
#![no_std]
#![no_core]
/*
* Core
*/
// Because we don't have core yet.
#[lang = "sized"]
pub trait Sized {}
#[lang = "copy"]
trait Copy {
}
impl Copy for isize {}
impl Copy for *mut i32 {}
impl Copy for usize {}
impl Copy for u8 {}
impl Copy for i8 {}
impl Copy for i32 {}
#[lang = "receiver"]
trait Receiver {
}
#[lang = "freeze"]
pub(crate) unsafe auto trait Freeze {}
#[lang = "panic_location"]
struct PanicLocation {
file: &'static str,
line: u32,
column: u32,
}
mod libc {
#[link(name = "c")]
extern "C" {
pub fn puts(s: *const u8) -> i32;
pub fn fflush(stream: *mut i32) -> i32;
pub fn printf(format: *const i8,...) -> i32;
pub static STDOUT: *mut i32;
}
}
mod intrinsics {
extern "rust-intrinsic" {
pub fn abort() ->!;
}
}
#[lang = "panic"]
#[track_caller]
#[no_mangle]
pub fn panic(_msg: &str) ->! {
unsafe {
libc::puts("Panicking\0" as *const str as *const u8);
libc::fflush(libc::STDOUT);
intrinsics::abort();
}
}
#[lang = "add"]
trait Add<RHS = Self> {
type Output;
fn add(self, rhs: RHS) -> Self::Output;
}
impl Add for u8 {
type Output = Self;
fn add(self, rhs: Self) -> Self {
self + rhs
}
}
impl Add for i8 {
type Output = Self;
fn add(self, rhs: Self) -> Self {
self + rhs
}
}
impl Add for i32 {
type Output = Self;
fn add(self, rhs: Self) -> Self {
self + rhs
}
}
impl Add for usize {
type Output = Self;
fn add(self, rhs: Self) -> Self {
self + rhs
}
}
impl Add for isize {
type Output = Self;
fn add(self, rhs: Self) -> Self {
self + rhs
}
}
/*
* Code
*/
struct Test {
field: isize,
}
fn test(num: isize) -> Test {
Test {
field: num + 1,
}
}
fn | (num: &mut isize) {
*num = *num + 5;
}
#[start]
fn main(mut argc: isize, _argv: *const *const u8) -> isize {
let mut test = test(argc);
unsafe {
libc::printf(b"%ld\n\0" as *const u8 as *const i8, test.field);
}
update_num(&mut test.field);
unsafe {
libc::printf(b"%ld\n\0" as *const u8 as *const i8, test.field);
}
update_num(&mut argc);
unsafe {
libc::printf(b"%ld\n\0" as *const u8 as *const i8, argc);
}
let refe = &mut argc;
*refe = *refe + 5;
unsafe {
libc::printf(b"%ld\n\0" as *const u8 as *const i8, argc);
}
0
}
| update_num | identifier_name |
issue-84973-blacklist.rs | // Checks that certain traits for which we don't want to suggest borrowing
// are blacklisted and don't cause the suggestion to be issued.
#![feature(generators)]
fn f_copy<T: Copy>(t: T) {}
fn f_clone<T: Clone>(t: T) {}
fn f_unpin<T: Unpin>(t: T) {}
fn f_sized<T: Sized>(t: T) {}
fn f_send<T: Send>(t: T) {}
struct S;
fn main() {
f_copy("".to_string()); //~ ERROR: the trait bound `String: Copy` is not satisfied [E0277]
f_clone(S); //~ ERROR: the trait bound `S: Clone` is not satisfied [E0277]
f_unpin(static || { yield; });
//~^ ERROR: cannot be unpinned [E0277]
let cl = || ();
let ref_cl: &dyn Fn() -> () = &cl;
f_sized(*ref_cl);
//~^ ERROR: the size for values of type `dyn Fn()` cannot be known at compilation time [E0277]
//~| ERROR: the size for values of type `dyn Fn()` cannot be known at compilation time [E0277]
use std::rc::Rc;
let rc = Rc::new(0);
f_send(rc); //~ ERROR: `Rc<{integer}>` cannot be sent between threads safely [E0277] | } | random_line_split |
|
issue-84973-blacklist.rs | // Checks that certain traits for which we don't want to suggest borrowing
// are blacklisted and don't cause the suggestion to be issued.
#![feature(generators)]
fn | <T: Copy>(t: T) {}
fn f_clone<T: Clone>(t: T) {}
fn f_unpin<T: Unpin>(t: T) {}
fn f_sized<T: Sized>(t: T) {}
fn f_send<T: Send>(t: T) {}
struct S;
fn main() {
f_copy("".to_string()); //~ ERROR: the trait bound `String: Copy` is not satisfied [E0277]
f_clone(S); //~ ERROR: the trait bound `S: Clone` is not satisfied [E0277]
f_unpin(static || { yield; });
//~^ ERROR: cannot be unpinned [E0277]
let cl = || ();
let ref_cl: &dyn Fn() -> () = &cl;
f_sized(*ref_cl);
//~^ ERROR: the size for values of type `dyn Fn()` cannot be known at compilation time [E0277]
//~| ERROR: the size for values of type `dyn Fn()` cannot be known at compilation time [E0277]
use std::rc::Rc;
let rc = Rc::new(0);
f_send(rc); //~ ERROR: `Rc<{integer}>` cannot be sent between threads safely [E0277]
}
| f_copy | identifier_name |
issue-84973-blacklist.rs | // Checks that certain traits for which we don't want to suggest borrowing
// are blacklisted and don't cause the suggestion to be issued.
#![feature(generators)]
fn f_copy<T: Copy>(t: T) {}
fn f_clone<T: Clone>(t: T) {}
fn f_unpin<T: Unpin>(t: T) |
fn f_sized<T: Sized>(t: T) {}
fn f_send<T: Send>(t: T) {}
struct S;
fn main() {
f_copy("".to_string()); //~ ERROR: the trait bound `String: Copy` is not satisfied [E0277]
f_clone(S); //~ ERROR: the trait bound `S: Clone` is not satisfied [E0277]
f_unpin(static || { yield; });
//~^ ERROR: cannot be unpinned [E0277]
let cl = || ();
let ref_cl: &dyn Fn() -> () = &cl;
f_sized(*ref_cl);
//~^ ERROR: the size for values of type `dyn Fn()` cannot be known at compilation time [E0277]
//~| ERROR: the size for values of type `dyn Fn()` cannot be known at compilation time [E0277]
use std::rc::Rc;
let rc = Rc::new(0);
f_send(rc); //~ ERROR: `Rc<{integer}>` cannot be sent between threads safely [E0277]
}
| {} | identifier_body |
path_parsing.rs | extern crate memchr;
use self::memchr::{memchr, memrchr};
use memrnchr::memrnchr;
use std::path::MAIN_SEPARATOR;
use std::str;
pub const SEP: u8 = MAIN_SEPARATOR as u8;
lazy_static! {
pub static ref SEP_STR: &'static str = str::from_utf8(&[SEP]).unwrap();
}
// Returns the byte offset of the last byte that equals MAIN_SEPARATOR.
#[inline(always)]
pub fn find_last_sep_pos(bytes: &[u8]) -> Option<usize> {
memrchr(SEP, bytes)
}
// Returns the byte offset of the last byte that is not MAIN_SEPARATOR.
#[inline(always)] | #[inline(always)]
pub fn contains_sep(bytes: &[u8]) -> bool {
memchr(SEP, bytes)!= None
} | pub fn find_last_non_sep_pos(bytes: &[u8]) -> Option<usize> {
memrnchr(SEP, bytes)
}
// Whether the given byte sequence contains a MAIN_SEPARATOR. | random_line_split |
path_parsing.rs | extern crate memchr;
use self::memchr::{memchr, memrchr};
use memrnchr::memrnchr;
use std::path::MAIN_SEPARATOR;
use std::str;
pub const SEP: u8 = MAIN_SEPARATOR as u8;
lazy_static! {
pub static ref SEP_STR: &'static str = str::from_utf8(&[SEP]).unwrap();
}
// Returns the byte offset of the last byte that equals MAIN_SEPARATOR.
#[inline(always)]
pub fn find_last_sep_pos(bytes: &[u8]) -> Option<usize> {
memrchr(SEP, bytes)
}
// Returns the byte offset of the last byte that is not MAIN_SEPARATOR.
#[inline(always)]
pub fn find_last_non_sep_pos(bytes: &[u8]) -> Option<usize> |
// Whether the given byte sequence contains a MAIN_SEPARATOR.
#[inline(always)]
pub fn contains_sep(bytes: &[u8]) -> bool {
memchr(SEP, bytes)!= None
}
| {
memrnchr(SEP, bytes)
} | identifier_body |
path_parsing.rs | extern crate memchr;
use self::memchr::{memchr, memrchr};
use memrnchr::memrnchr;
use std::path::MAIN_SEPARATOR;
use std::str;
pub const SEP: u8 = MAIN_SEPARATOR as u8;
lazy_static! {
pub static ref SEP_STR: &'static str = str::from_utf8(&[SEP]).unwrap();
}
// Returns the byte offset of the last byte that equals MAIN_SEPARATOR.
#[inline(always)]
pub fn find_last_sep_pos(bytes: &[u8]) -> Option<usize> {
memrchr(SEP, bytes)
}
// Returns the byte offset of the last byte that is not MAIN_SEPARATOR.
#[inline(always)]
pub fn find_last_non_sep_pos(bytes: &[u8]) -> Option<usize> {
memrnchr(SEP, bytes)
}
// Whether the given byte sequence contains a MAIN_SEPARATOR.
#[inline(always)]
pub fn | (bytes: &[u8]) -> bool {
memchr(SEP, bytes)!= None
}
| contains_sep | identifier_name |
instr_cvtdq2ps.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
use ::test::run_test;
#[test]
fn cvtdq2ps_1() |
#[test]
fn cvtdq2ps_2() {
run_test(&Instruction { mnemonic: Mnemonic::CVTDQ2PS, operand1: Some(Direct(XMM6)), operand2: Some(IndirectScaledDisplaced(ECX, Two, 829617393, Some(OperandSize::Xmmword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[15, 91, 52, 77, 241, 244, 114, 49], OperandSize::Dword)
}
#[test]
fn cvtdq2ps_3() {
run_test(&Instruction { mnemonic: Mnemonic::CVTDQ2PS, operand1: Some(Direct(XMM6)), operand2: Some(Direct(XMM4)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[15, 91, 244], OperandSize::Qword)
}
#[test]
fn cvtdq2ps_4() {
run_test(&Instruction { mnemonic: Mnemonic::CVTDQ2PS, operand1: Some(Direct(XMM2)), operand2: Some(IndirectScaledDisplaced(RBX, Two, 1952076968, Some(OperandSize::Xmmword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[15, 91, 20, 93, 168, 84, 90, 116], OperandSize::Qword)
}
| {
run_test(&Instruction { mnemonic: Mnemonic::CVTDQ2PS, operand1: Some(Direct(XMM2)), operand2: Some(Direct(XMM2)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[15, 91, 210], OperandSize::Dword)
} | identifier_body |
instr_cvtdq2ps.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
use ::test::run_test;
#[test]
fn cvtdq2ps_1() {
run_test(&Instruction { mnemonic: Mnemonic::CVTDQ2PS, operand1: Some(Direct(XMM2)), operand2: Some(Direct(XMM2)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[15, 91, 210], OperandSize::Dword)
}
#[test]
fn cvtdq2ps_2() {
run_test(&Instruction { mnemonic: Mnemonic::CVTDQ2PS, operand1: Some(Direct(XMM6)), operand2: Some(IndirectScaledDisplaced(ECX, Two, 829617393, Some(OperandSize::Xmmword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[15, 91, 52, 77, 241, 244, 114, 49], OperandSize::Dword)
}
#[test]
fn cvtdq2ps_3() {
run_test(&Instruction { mnemonic: Mnemonic::CVTDQ2PS, operand1: Some(Direct(XMM6)), operand2: Some(Direct(XMM4)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[15, 91, 244], OperandSize::Qword)
}
#[test]
fn | () {
run_test(&Instruction { mnemonic: Mnemonic::CVTDQ2PS, operand1: Some(Direct(XMM2)), operand2: Some(IndirectScaledDisplaced(RBX, Two, 1952076968, Some(OperandSize::Xmmword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[15, 91, 20, 93, 168, 84, 90, 116], OperandSize::Qword)
}
| cvtdq2ps_4 | identifier_name |
instr_cvtdq2ps.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
use ::test::run_test;
#[test] | fn cvtdq2ps_1() {
run_test(&Instruction { mnemonic: Mnemonic::CVTDQ2PS, operand1: Some(Direct(XMM2)), operand2: Some(Direct(XMM2)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[15, 91, 210], OperandSize::Dword)
}
#[test]
fn cvtdq2ps_2() {
run_test(&Instruction { mnemonic: Mnemonic::CVTDQ2PS, operand1: Some(Direct(XMM6)), operand2: Some(IndirectScaledDisplaced(ECX, Two, 829617393, Some(OperandSize::Xmmword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[15, 91, 52, 77, 241, 244, 114, 49], OperandSize::Dword)
}
#[test]
fn cvtdq2ps_3() {
run_test(&Instruction { mnemonic: Mnemonic::CVTDQ2PS, operand1: Some(Direct(XMM6)), operand2: Some(Direct(XMM4)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[15, 91, 244], OperandSize::Qword)
}
#[test]
fn cvtdq2ps_4() {
run_test(&Instruction { mnemonic: Mnemonic::CVTDQ2PS, operand1: Some(Direct(XMM2)), operand2: Some(IndirectScaledDisplaced(RBX, Two, 1952076968, Some(OperandSize::Xmmword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[15, 91, 20, 93, 168, 84, 90, 116], OperandSize::Qword)
} | random_line_split |
|
mut-ptr-cant-outlive-ref.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::cell::RefCell;
fn main() |
trait Fake { fn use_mut(&mut self) { } fn use_ref(&self) { } }
impl<T> Fake for T { }
| {
let m = RefCell::new(0);
let p;
{
let b = m.borrow();
p = &*b;
}
//~^^ ERROR `b` does not live long enough
p.use_ref();
} | identifier_body |
mut-ptr-cant-outlive-ref.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::cell::RefCell;
fn main() {
let m = RefCell::new(0);
let p;
{
let b = m.borrow();
p = &*b;
}
//~^^ ERROR `b` does not live long enough
p.use_ref();
}
trait Fake { fn | (&mut self) { } fn use_ref(&self) { } }
impl<T> Fake for T { }
| use_mut | identifier_name |
mut-ptr-cant-outlive-ref.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT. | // option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::cell::RefCell;
fn main() {
let m = RefCell::new(0);
let p;
{
let b = m.borrow();
p = &*b;
}
//~^^ ERROR `b` does not live long enough
p.use_ref();
}
trait Fake { fn use_mut(&mut self) { } fn use_ref(&self) { } }
impl<T> Fake for T { } | //
// 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 | random_line_split |
cursor.rs | // Copyright 2013-2015, The Gtk-rs Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
use glib::translate::*;
use display::Display;
use pixbuf::Pixbuf;
use ffi;
pub type Type = ffi::GdkCursorType;
glib_wrapper! {
pub struct Cursor(Object<ffi::GdkCursor>);
match fn {
get_type => || ffi::gdk_cursor_get_type(),
}
}
impl Cursor {
pub fn new(cursor_type: Type) -> Cursor {
assert_initialized_main_thread!();
unsafe { from_glib_full(ffi::gdk_cursor_new(cursor_type)) }
}
pub fn | (display: &Display, pixbuf: &Pixbuf, x: i32, y: i32) -> Cursor {
skip_assert_initialized!();
unsafe {
from_glib_full(
ffi::gdk_cursor_new_from_pixbuf(display.to_glib_none().0,
pixbuf.to_glib_none().0, x, y))
}
}
pub fn new_from_name(display: &Display, name: &str) -> Option<Cursor> {
skip_assert_initialized!();
unsafe {
from_glib_full(ffi::gdk_cursor_new_from_name(display.to_glib_none().0,
name.to_glib_none().0))
}
}
pub fn new_for_display(display: &Display, cursor_type: Type) -> Cursor {
skip_assert_initialized!();
unsafe {
from_glib_full(ffi::gdk_cursor_new_for_display(display.to_glib_none().0, cursor_type))
}
}
pub fn get_display(&self) -> Display {
unsafe { from_glib_none(ffi::gdk_cursor_get_display(self.to_glib_none().0)) }
}
pub fn get_image(&self) -> Option<Pixbuf> {
unsafe { from_glib_full(ffi::gdk_cursor_get_image(self.to_glib_none().0)) }
}
pub fn get_cursor_type(&self) -> Type {
unsafe { ffi::gdk_cursor_get_cursor_type(self.to_glib_none().0) }
}
}
| new_from_pixbuf | identifier_name |
cursor.rs | // Copyright 2013-2015, The Gtk-rs Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
use glib::translate::*;
use display::Display;
use pixbuf::Pixbuf;
use ffi;
pub type Type = ffi::GdkCursorType;
glib_wrapper! {
pub struct Cursor(Object<ffi::GdkCursor>);
match fn {
get_type => || ffi::gdk_cursor_get_type(),
}
}
impl Cursor { | }
pub fn new_from_pixbuf(display: &Display, pixbuf: &Pixbuf, x: i32, y: i32) -> Cursor {
skip_assert_initialized!();
unsafe {
from_glib_full(
ffi::gdk_cursor_new_from_pixbuf(display.to_glib_none().0,
pixbuf.to_glib_none().0, x, y))
}
}
pub fn new_from_name(display: &Display, name: &str) -> Option<Cursor> {
skip_assert_initialized!();
unsafe {
from_glib_full(ffi::gdk_cursor_new_from_name(display.to_glib_none().0,
name.to_glib_none().0))
}
}
pub fn new_for_display(display: &Display, cursor_type: Type) -> Cursor {
skip_assert_initialized!();
unsafe {
from_glib_full(ffi::gdk_cursor_new_for_display(display.to_glib_none().0, cursor_type))
}
}
pub fn get_display(&self) -> Display {
unsafe { from_glib_none(ffi::gdk_cursor_get_display(self.to_glib_none().0)) }
}
pub fn get_image(&self) -> Option<Pixbuf> {
unsafe { from_glib_full(ffi::gdk_cursor_get_image(self.to_glib_none().0)) }
}
pub fn get_cursor_type(&self) -> Type {
unsafe { ffi::gdk_cursor_get_cursor_type(self.to_glib_none().0) }
}
} | pub fn new(cursor_type: Type) -> Cursor {
assert_initialized_main_thread!();
unsafe { from_glib_full(ffi::gdk_cursor_new(cursor_type)) } | random_line_split |
cursor.rs | // Copyright 2013-2015, The Gtk-rs Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
use glib::translate::*;
use display::Display;
use pixbuf::Pixbuf;
use ffi;
pub type Type = ffi::GdkCursorType;
glib_wrapper! {
pub struct Cursor(Object<ffi::GdkCursor>);
match fn {
get_type => || ffi::gdk_cursor_get_type(),
}
}
impl Cursor {
pub fn new(cursor_type: Type) -> Cursor {
assert_initialized_main_thread!();
unsafe { from_glib_full(ffi::gdk_cursor_new(cursor_type)) }
}
pub fn new_from_pixbuf(display: &Display, pixbuf: &Pixbuf, x: i32, y: i32) -> Cursor {
skip_assert_initialized!();
unsafe {
from_glib_full(
ffi::gdk_cursor_new_from_pixbuf(display.to_glib_none().0,
pixbuf.to_glib_none().0, x, y))
}
}
pub fn new_from_name(display: &Display, name: &str) -> Option<Cursor> {
skip_assert_initialized!();
unsafe {
from_glib_full(ffi::gdk_cursor_new_from_name(display.to_glib_none().0,
name.to_glib_none().0))
}
}
pub fn new_for_display(display: &Display, cursor_type: Type) -> Cursor {
skip_assert_initialized!();
unsafe {
from_glib_full(ffi::gdk_cursor_new_for_display(display.to_glib_none().0, cursor_type))
}
}
pub fn get_display(&self) -> Display {
unsafe { from_glib_none(ffi::gdk_cursor_get_display(self.to_glib_none().0)) }
}
pub fn get_image(&self) -> Option<Pixbuf> {
unsafe { from_glib_full(ffi::gdk_cursor_get_image(self.to_glib_none().0)) }
}
pub fn get_cursor_type(&self) -> Type |
}
| {
unsafe { ffi::gdk_cursor_get_cursor_type(self.to_glib_none().0) }
} | identifier_body |
issue-59523-on-implemented-is-not-unused.rs | // We should not see the unused_attributes lint fire for
// rustc_on_unimplemented, but with this bug we are seeing it fire (on
// subsequent runs) if incremental compilation is enabled.
// revisions: cfail1 cfail2
// build-pass (FIXME(62277): could be check-pass?)
#![feature(rustc_attrs)]
#![deny(unused_attributes)]
#[rustc_on_unimplemented = "invalid"]
trait Index<Idx:?Sized> {
type Output:?Sized;
fn index(&self, index: Idx) -> &Self::Output;
}
#[rustc_on_unimplemented = "a usize is required to index into a slice"]
impl Index<usize> for [i32] {
type Output = i32;
fn | (&self, index: usize) -> &i32 {
&self[index]
}
}
fn main() {
Index::<usize>::index(&[1, 2, 3] as &[i32], 2);
}
| index | identifier_name |
issue-59523-on-implemented-is-not-unused.rs | // We should not see the unused_attributes lint fire for
// rustc_on_unimplemented, but with this bug we are seeing it fire (on
// subsequent runs) if incremental compilation is enabled.
// revisions: cfail1 cfail2
// build-pass (FIXME(62277): could be check-pass?)
#![feature(rustc_attrs)]
#![deny(unused_attributes)]
#[rustc_on_unimplemented = "invalid"]
trait Index<Idx:?Sized> {
type Output:?Sized;
fn index(&self, index: Idx) -> &Self::Output;
}
#[rustc_on_unimplemented = "a usize is required to index into a slice"]
impl Index<usize> for [i32] {
type Output = i32;
fn index(&self, index: usize) -> &i32 {
&self[index]
}
}
fn main() | {
Index::<usize>::index(&[1, 2, 3] as &[i32], 2);
} | identifier_body |
|
bench.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use cssparser::{Parser, SourcePosition};
use parking_lot::RwLock;
use rayon;
use servo_url::ServoUrl;
use std::sync::Arc;
use style::error_reporting::ParseErrorReporter;
use style::media_queries::MediaList;
use style::parser::ParserContextExtraData;
use style::properties::{longhands, Importance, PropertyDeclaration, PropertyDeclarationBlock};
use style::rule_tree::{CascadeLevel, RuleTree, StrongRuleNode, StyleSource};
use style::stylesheets::{Origin, Stylesheet, CssRule};
use test::{self, Bencher};
struct ErrorringErrorReporter;
impl ParseErrorReporter for ErrorringErrorReporter {
fn report_error(&self, _input: &mut Parser, position: SourcePosition, message: &str,
url: &ServoUrl) {
panic!("CSS error: {}\t\n{:?} {}", url.as_str(), position, message);
}
}
struct AutoGCRuleTree<'a>(&'a RuleTree);
impl<'a> AutoGCRuleTree<'a> {
fn new(r: &'a RuleTree) -> Self {
AutoGCRuleTree(r)
}
}
impl<'a> Drop for AutoGCRuleTree<'a> {
fn drop(&mut self) {
unsafe { self.0.gc() }
}
}
fn parse_rules(css: &str) -> Vec<(StyleSource, CascadeLevel)> {
let s = Stylesheet::from_str(css,
ServoUrl::parse("http://localhost").unwrap(),
Origin::Author,
MediaList {
media_queries: vec![],
},
None,
&ErrorringErrorReporter,
ParserContextExtraData {});
let rules = s.rules.read();
rules.0.iter().filter_map(|rule| {
match *rule {
CssRule::Style(ref style_rule) => Some(style_rule),
_ => None,
}
}).cloned().map(StyleSource::Style).map(|s| {
(s, CascadeLevel::UserNormal)
}).collect()
}
fn test_insertion(rule_tree: &RuleTree, rules: Vec<(StyleSource, CascadeLevel)>) -> StrongRuleNode {
rule_tree.insert_ordered_rules(rules.into_iter())
}
fn test_insertion_style_attribute(rule_tree: &RuleTree, rules: &[(StyleSource, CascadeLevel)]) -> StrongRuleNode {
let mut rules = rules.to_vec();
rules.push((StyleSource::Declarations(Arc::new(RwLock::new(PropertyDeclarationBlock::with_one(
PropertyDeclaration::Display(
longhands::display::SpecifiedValue::block),
Importance::Normal
)))), CascadeLevel::UserNormal));
test_insertion(rule_tree, rules)
}
#[bench]
fn bench_insertion_basic(b: &mut Bencher) {
let r = RuleTree::new();
let rules_matched = parse_rules(
".foo { width: 200px; } \
.bar { height: 500px; } \
.baz { display: block; }");
b.iter(|| {
let _gc = AutoGCRuleTree::new(&r);
for _ in 0..(4000 + 400) {
test::black_box(test_insertion(&r, rules_matched.clone()));
}
})
}
#[bench]
fn bench_insertion_basic_per_element(b: &mut Bencher) {
let r = RuleTree::new();
let rules_matched = parse_rules(
".foo { width: 200px; } \
.bar { height: 500px; } \
.baz { display: block; }");
b.iter(|| {
let _gc = AutoGCRuleTree::new(&r);
test::black_box(test_insertion(&r, rules_matched.clone()));
});
}
#[bench]
fn bench_expensive_insertion(b: &mut Bencher) {
let r = RuleTree::new();
// This test case tests a case where you style a bunch of siblings
// matching the same rules, with a different style attribute each
// one.
let rules_matched = parse_rules(
".foo { width: 200px; } \
.bar { height: 500px; } \
.baz { display: block; }");
b.iter(|| {
let _gc = AutoGCRuleTree::new(&r);
for _ in 0..(4000 + 400) {
test::black_box(test_insertion_style_attribute(&r, &rules_matched));
}
});
}
#[bench]
fn bench_insertion_basic_parallel(b: &mut Bencher) {
let r = RuleTree::new();
let rules_matched = parse_rules(
".foo { width: 200px; } \
.bar { height: 500px; } \
.baz { display: block; }");
b.iter(|| {
let _gc = AutoGCRuleTree::new(&r);
rayon::scope(|s| {
for _ in 0..4 {
s.spawn(|s| {
for _ in 0..1000 {
test::black_box(test_insertion(&r,
rules_matched.clone()));
}
s.spawn(|_| {
for _ in 0..100 {
test::black_box(test_insertion(&r,
rules_matched.clone()));
}
})
})
}
});
});
}
#[bench]
fn bench_expensive_insersion_parallel(b: &mut Bencher) {
let r = RuleTree::new();
let rules_matched = parse_rules(
".foo { width: 200px; } \
.bar { height: 500px; } \
.baz { display: block; }");
b.iter(|| {
let _gc = AutoGCRuleTree::new(&r);
rayon::scope(|s| {
for _ in 0..4 {
s.spawn(|s| {
for _ in 0..1000 { | test::black_box(test_insertion_style_attribute(&r,
&rules_matched));
}
})
})
}
});
});
} | test::black_box(test_insertion_style_attribute(&r,
&rules_matched));
}
s.spawn(|_| {
for _ in 0..100 { | random_line_split |
bench.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use cssparser::{Parser, SourcePosition};
use parking_lot::RwLock;
use rayon;
use servo_url::ServoUrl;
use std::sync::Arc;
use style::error_reporting::ParseErrorReporter;
use style::media_queries::MediaList;
use style::parser::ParserContextExtraData;
use style::properties::{longhands, Importance, PropertyDeclaration, PropertyDeclarationBlock};
use style::rule_tree::{CascadeLevel, RuleTree, StrongRuleNode, StyleSource};
use style::stylesheets::{Origin, Stylesheet, CssRule};
use test::{self, Bencher};
struct ErrorringErrorReporter;
impl ParseErrorReporter for ErrorringErrorReporter {
fn report_error(&self, _input: &mut Parser, position: SourcePosition, message: &str,
url: &ServoUrl) {
panic!("CSS error: {}\t\n{:?} {}", url.as_str(), position, message);
}
}
struct AutoGCRuleTree<'a>(&'a RuleTree);
impl<'a> AutoGCRuleTree<'a> {
fn new(r: &'a RuleTree) -> Self {
AutoGCRuleTree(r)
}
}
impl<'a> Drop for AutoGCRuleTree<'a> {
fn drop(&mut self) {
unsafe { self.0.gc() }
}
}
fn parse_rules(css: &str) -> Vec<(StyleSource, CascadeLevel)> |
fn test_insertion(rule_tree: &RuleTree, rules: Vec<(StyleSource, CascadeLevel)>) -> StrongRuleNode {
rule_tree.insert_ordered_rules(rules.into_iter())
}
fn test_insertion_style_attribute(rule_tree: &RuleTree, rules: &[(StyleSource, CascadeLevel)]) -> StrongRuleNode {
let mut rules = rules.to_vec();
rules.push((StyleSource::Declarations(Arc::new(RwLock::new(PropertyDeclarationBlock::with_one(
PropertyDeclaration::Display(
longhands::display::SpecifiedValue::block),
Importance::Normal
)))), CascadeLevel::UserNormal));
test_insertion(rule_tree, rules)
}
#[bench]
fn bench_insertion_basic(b: &mut Bencher) {
let r = RuleTree::new();
let rules_matched = parse_rules(
".foo { width: 200px; } \
.bar { height: 500px; } \
.baz { display: block; }");
b.iter(|| {
let _gc = AutoGCRuleTree::new(&r);
for _ in 0..(4000 + 400) {
test::black_box(test_insertion(&r, rules_matched.clone()));
}
})
}
#[bench]
fn bench_insertion_basic_per_element(b: &mut Bencher) {
let r = RuleTree::new();
let rules_matched = parse_rules(
".foo { width: 200px; } \
.bar { height: 500px; } \
.baz { display: block; }");
b.iter(|| {
let _gc = AutoGCRuleTree::new(&r);
test::black_box(test_insertion(&r, rules_matched.clone()));
});
}
#[bench]
fn bench_expensive_insertion(b: &mut Bencher) {
let r = RuleTree::new();
// This test case tests a case where you style a bunch of siblings
// matching the same rules, with a different style attribute each
// one.
let rules_matched = parse_rules(
".foo { width: 200px; } \
.bar { height: 500px; } \
.baz { display: block; }");
b.iter(|| {
let _gc = AutoGCRuleTree::new(&r);
for _ in 0..(4000 + 400) {
test::black_box(test_insertion_style_attribute(&r, &rules_matched));
}
});
}
#[bench]
fn bench_insertion_basic_parallel(b: &mut Bencher) {
let r = RuleTree::new();
let rules_matched = parse_rules(
".foo { width: 200px; } \
.bar { height: 500px; } \
.baz { display: block; }");
b.iter(|| {
let _gc = AutoGCRuleTree::new(&r);
rayon::scope(|s| {
for _ in 0..4 {
s.spawn(|s| {
for _ in 0..1000 {
test::black_box(test_insertion(&r,
rules_matched.clone()));
}
s.spawn(|_| {
for _ in 0..100 {
test::black_box(test_insertion(&r,
rules_matched.clone()));
}
})
})
}
});
});
}
#[bench]
fn bench_expensive_insersion_parallel(b: &mut Bencher) {
let r = RuleTree::new();
let rules_matched = parse_rules(
".foo { width: 200px; } \
.bar { height: 500px; } \
.baz { display: block; }");
b.iter(|| {
let _gc = AutoGCRuleTree::new(&r);
rayon::scope(|s| {
for _ in 0..4 {
s.spawn(|s| {
for _ in 0..1000 {
test::black_box(test_insertion_style_attribute(&r,
&rules_matched));
}
s.spawn(|_| {
for _ in 0..100 {
test::black_box(test_insertion_style_attribute(&r,
&rules_matched));
}
})
})
}
});
});
}
| {
let s = Stylesheet::from_str(css,
ServoUrl::parse("http://localhost").unwrap(),
Origin::Author,
MediaList {
media_queries: vec![],
},
None,
&ErrorringErrorReporter,
ParserContextExtraData {});
let rules = s.rules.read();
rules.0.iter().filter_map(|rule| {
match *rule {
CssRule::Style(ref style_rule) => Some(style_rule),
_ => None,
}
}).cloned().map(StyleSource::Style).map(|s| {
(s, CascadeLevel::UserNormal)
}).collect()
} | identifier_body |
bench.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use cssparser::{Parser, SourcePosition};
use parking_lot::RwLock;
use rayon;
use servo_url::ServoUrl;
use std::sync::Arc;
use style::error_reporting::ParseErrorReporter;
use style::media_queries::MediaList;
use style::parser::ParserContextExtraData;
use style::properties::{longhands, Importance, PropertyDeclaration, PropertyDeclarationBlock};
use style::rule_tree::{CascadeLevel, RuleTree, StrongRuleNode, StyleSource};
use style::stylesheets::{Origin, Stylesheet, CssRule};
use test::{self, Bencher};
struct ErrorringErrorReporter;
impl ParseErrorReporter for ErrorringErrorReporter {
fn report_error(&self, _input: &mut Parser, position: SourcePosition, message: &str,
url: &ServoUrl) {
panic!("CSS error: {}\t\n{:?} {}", url.as_str(), position, message);
}
}
struct AutoGCRuleTree<'a>(&'a RuleTree);
impl<'a> AutoGCRuleTree<'a> {
fn new(r: &'a RuleTree) -> Self {
AutoGCRuleTree(r)
}
}
impl<'a> Drop for AutoGCRuleTree<'a> {
fn drop(&mut self) {
unsafe { self.0.gc() }
}
}
fn parse_rules(css: &str) -> Vec<(StyleSource, CascadeLevel)> {
let s = Stylesheet::from_str(css,
ServoUrl::parse("http://localhost").unwrap(),
Origin::Author,
MediaList {
media_queries: vec![],
},
None,
&ErrorringErrorReporter,
ParserContextExtraData {});
let rules = s.rules.read();
rules.0.iter().filter_map(|rule| {
match *rule {
CssRule::Style(ref style_rule) => Some(style_rule),
_ => None,
}
}).cloned().map(StyleSource::Style).map(|s| {
(s, CascadeLevel::UserNormal)
}).collect()
}
fn test_insertion(rule_tree: &RuleTree, rules: Vec<(StyleSource, CascadeLevel)>) -> StrongRuleNode {
rule_tree.insert_ordered_rules(rules.into_iter())
}
fn test_insertion_style_attribute(rule_tree: &RuleTree, rules: &[(StyleSource, CascadeLevel)]) -> StrongRuleNode {
let mut rules = rules.to_vec();
rules.push((StyleSource::Declarations(Arc::new(RwLock::new(PropertyDeclarationBlock::with_one(
PropertyDeclaration::Display(
longhands::display::SpecifiedValue::block),
Importance::Normal
)))), CascadeLevel::UserNormal));
test_insertion(rule_tree, rules)
}
#[bench]
fn bench_insertion_basic(b: &mut Bencher) {
let r = RuleTree::new();
let rules_matched = parse_rules(
".foo { width: 200px; } \
.bar { height: 500px; } \
.baz { display: block; }");
b.iter(|| {
let _gc = AutoGCRuleTree::new(&r);
for _ in 0..(4000 + 400) {
test::black_box(test_insertion(&r, rules_matched.clone()));
}
})
}
#[bench]
fn bench_insertion_basic_per_element(b: &mut Bencher) {
let r = RuleTree::new();
let rules_matched = parse_rules(
".foo { width: 200px; } \
.bar { height: 500px; } \
.baz { display: block; }");
b.iter(|| {
let _gc = AutoGCRuleTree::new(&r);
test::black_box(test_insertion(&r, rules_matched.clone()));
});
}
#[bench]
fn | (b: &mut Bencher) {
let r = RuleTree::new();
// This test case tests a case where you style a bunch of siblings
// matching the same rules, with a different style attribute each
// one.
let rules_matched = parse_rules(
".foo { width: 200px; } \
.bar { height: 500px; } \
.baz { display: block; }");
b.iter(|| {
let _gc = AutoGCRuleTree::new(&r);
for _ in 0..(4000 + 400) {
test::black_box(test_insertion_style_attribute(&r, &rules_matched));
}
});
}
#[bench]
fn bench_insertion_basic_parallel(b: &mut Bencher) {
let r = RuleTree::new();
let rules_matched = parse_rules(
".foo { width: 200px; } \
.bar { height: 500px; } \
.baz { display: block; }");
b.iter(|| {
let _gc = AutoGCRuleTree::new(&r);
rayon::scope(|s| {
for _ in 0..4 {
s.spawn(|s| {
for _ in 0..1000 {
test::black_box(test_insertion(&r,
rules_matched.clone()));
}
s.spawn(|_| {
for _ in 0..100 {
test::black_box(test_insertion(&r,
rules_matched.clone()));
}
})
})
}
});
});
}
#[bench]
fn bench_expensive_insersion_parallel(b: &mut Bencher) {
let r = RuleTree::new();
let rules_matched = parse_rules(
".foo { width: 200px; } \
.bar { height: 500px; } \
.baz { display: block; }");
b.iter(|| {
let _gc = AutoGCRuleTree::new(&r);
rayon::scope(|s| {
for _ in 0..4 {
s.spawn(|s| {
for _ in 0..1000 {
test::black_box(test_insertion_style_attribute(&r,
&rules_matched));
}
s.spawn(|_| {
for _ in 0..100 {
test::black_box(test_insertion_style_attribute(&r,
&rules_matched));
}
})
})
}
});
});
}
| bench_expensive_insertion | identifier_name |
instr_rsqrtps.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
use ::test::run_test;
#[test]
fn rsqrtps_1() {
run_test(&Instruction { mnemonic: Mnemonic::RSQRTPS, operand1: Some(Direct(XMM2)), operand2: Some(Direct(XMM6)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[15, 82, 214], OperandSize::Dword)
}
#[test]
fn rsqrtps_2() {
run_test(&Instruction { mnemonic: Mnemonic::RSQRTPS, operand1: Some(Direct(XMM7)), operand2: Some(IndirectScaledDisplaced(EAX, Two, 1571527684, Some(OperandSize::Xmmword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[15, 82, 60, 69, 4, 156, 171, 93], OperandSize::Dword)
}
#[test]
fn rsqrtps_3() {
run_test(&Instruction { mnemonic: Mnemonic::RSQRTPS, operand1: Some(Direct(XMM0)), operand2: Some(Direct(XMM4)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[15, 82, 196], OperandSize::Qword)
}
#[test]
fn rsqrtps_4() | {
run_test(&Instruction { mnemonic: Mnemonic::RSQRTPS, operand1: Some(Direct(XMM3)), operand2: Some(IndirectScaledIndexed(RDX, RDX, Four, Some(OperandSize::Xmmword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[15, 82, 28, 146], OperandSize::Qword)
} | identifier_body |
|
instr_rsqrtps.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*; | use ::RegScale::*;
use ::test::run_test;
#[test]
fn rsqrtps_1() {
run_test(&Instruction { mnemonic: Mnemonic::RSQRTPS, operand1: Some(Direct(XMM2)), operand2: Some(Direct(XMM6)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[15, 82, 214], OperandSize::Dword)
}
#[test]
fn rsqrtps_2() {
run_test(&Instruction { mnemonic: Mnemonic::RSQRTPS, operand1: Some(Direct(XMM7)), operand2: Some(IndirectScaledDisplaced(EAX, Two, 1571527684, Some(OperandSize::Xmmword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[15, 82, 60, 69, 4, 156, 171, 93], OperandSize::Dword)
}
#[test]
fn rsqrtps_3() {
run_test(&Instruction { mnemonic: Mnemonic::RSQRTPS, operand1: Some(Direct(XMM0)), operand2: Some(Direct(XMM4)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[15, 82, 196], OperandSize::Qword)
}
#[test]
fn rsqrtps_4() {
run_test(&Instruction { mnemonic: Mnemonic::RSQRTPS, operand1: Some(Direct(XMM3)), operand2: Some(IndirectScaledIndexed(RDX, RDX, Four, Some(OperandSize::Xmmword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[15, 82, 28, 146], OperandSize::Qword)
} | use ::Operand::*;
use ::Reg::*; | random_line_split |
instr_rsqrtps.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
use ::test::run_test;
#[test]
fn rsqrtps_1() {
run_test(&Instruction { mnemonic: Mnemonic::RSQRTPS, operand1: Some(Direct(XMM2)), operand2: Some(Direct(XMM6)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[15, 82, 214], OperandSize::Dword)
}
#[test]
fn rsqrtps_2() {
run_test(&Instruction { mnemonic: Mnemonic::RSQRTPS, operand1: Some(Direct(XMM7)), operand2: Some(IndirectScaledDisplaced(EAX, Two, 1571527684, Some(OperandSize::Xmmword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[15, 82, 60, 69, 4, 156, 171, 93], OperandSize::Dword)
}
#[test]
fn | () {
run_test(&Instruction { mnemonic: Mnemonic::RSQRTPS, operand1: Some(Direct(XMM0)), operand2: Some(Direct(XMM4)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[15, 82, 196], OperandSize::Qword)
}
#[test]
fn rsqrtps_4() {
run_test(&Instruction { mnemonic: Mnemonic::RSQRTPS, operand1: Some(Direct(XMM3)), operand2: Some(IndirectScaledIndexed(RDX, RDX, Four, Some(OperandSize::Xmmword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[15, 82, 28, 146], OperandSize::Qword)
}
| rsqrtps_3 | identifier_name |
target.rs | use std::str::FromStr;
use once_cell::sync::Lazy;
use regex::Regex;
#[derive(Debug)]
pub enum Target {
Amd64Linux,
Arm64Linux,
ArmLinux,
ArmV7Linux,
ArmV7LinuxHardFloat,
}
impl Target {
pub fn try_parse_env() -> Result<Target, <Self as FromStr>::Err> {
FromStr::from_str(env!("BUILD_TARGET"))
}
}
impl FromStr for Target {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
x if x.starts_with("x86_64-unknown-linux-") => Ok(Target::Amd64Linux),
x if x.starts_with("aarch64-unknown-linux-") => Ok(Target::Arm64Linux),
x if ARMV7_HARD_FLOAT.is_match(x) => Ok(Target::ArmV7LinuxHardFloat),
x if x.starts_with("armv7-unknown-linux") => Ok(Target::ArmV7Linux),
"arm-unknown-linux-musleabi" => Ok(Target::ArmLinux),
_ => Err(s.to_string()),
}
}
}
static ARMV7_HARD_FLOAT: Lazy<Regex> =
Lazy::new(|| Regex::new(r"armv7-unknown-linux.*hf").unwrap());
| #[test]
fn test_armv7_hard_float_matcher() {
assert!(ARMV7_HARD_FLOAT.is_match("armv7-unknown-linux-gnueabihf"));
assert!(ARMV7_HARD_FLOAT.is_match("armv7-unknown-linux-musleabihf"));
}
} | #[cfg(test)]
mod tests {
use super::*;
| random_line_split |
target.rs | use std::str::FromStr;
use once_cell::sync::Lazy;
use regex::Regex;
#[derive(Debug)]
pub enum Target {
Amd64Linux,
Arm64Linux,
ArmLinux,
ArmV7Linux,
ArmV7LinuxHardFloat,
}
impl Target {
pub fn try_parse_env() -> Result<Target, <Self as FromStr>::Err> {
FromStr::from_str(env!("BUILD_TARGET"))
}
}
impl FromStr for Target {
type Err = String;
fn | (s: &str) -> Result<Self, Self::Err> {
match s {
x if x.starts_with("x86_64-unknown-linux-") => Ok(Target::Amd64Linux),
x if x.starts_with("aarch64-unknown-linux-") => Ok(Target::Arm64Linux),
x if ARMV7_HARD_FLOAT.is_match(x) => Ok(Target::ArmV7LinuxHardFloat),
x if x.starts_with("armv7-unknown-linux") => Ok(Target::ArmV7Linux),
"arm-unknown-linux-musleabi" => Ok(Target::ArmLinux),
_ => Err(s.to_string()),
}
}
}
static ARMV7_HARD_FLOAT: Lazy<Regex> =
Lazy::new(|| Regex::new(r"armv7-unknown-linux.*hf").unwrap());
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_armv7_hard_float_matcher() {
assert!(ARMV7_HARD_FLOAT.is_match("armv7-unknown-linux-gnueabihf"));
assert!(ARMV7_HARD_FLOAT.is_match("armv7-unknown-linux-musleabihf"));
}
}
| from_str | identifier_name |
target.rs | use std::str::FromStr;
use once_cell::sync::Lazy;
use regex::Regex;
#[derive(Debug)]
pub enum Target {
Amd64Linux,
Arm64Linux,
ArmLinux,
ArmV7Linux,
ArmV7LinuxHardFloat,
}
impl Target {
pub fn try_parse_env() -> Result<Target, <Self as FromStr>::Err> {
FromStr::from_str(env!("BUILD_TARGET"))
}
}
impl FromStr for Target {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> |
}
static ARMV7_HARD_FLOAT: Lazy<Regex> =
Lazy::new(|| Regex::new(r"armv7-unknown-linux.*hf").unwrap());
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_armv7_hard_float_matcher() {
assert!(ARMV7_HARD_FLOAT.is_match("armv7-unknown-linux-gnueabihf"));
assert!(ARMV7_HARD_FLOAT.is_match("armv7-unknown-linux-musleabihf"));
}
}
| {
match s {
x if x.starts_with("x86_64-unknown-linux-") => Ok(Target::Amd64Linux),
x if x.starts_with("aarch64-unknown-linux-") => Ok(Target::Arm64Linux),
x if ARMV7_HARD_FLOAT.is_match(x) => Ok(Target::ArmV7LinuxHardFloat),
x if x.starts_with("armv7-unknown-linux") => Ok(Target::ArmV7Linux),
"arm-unknown-linux-musleabi" => Ok(Target::ArmLinux),
_ => Err(s.to_string()),
}
} | identifier_body |
lib.rs | //! A macro that maps unicode names to chars and strings.
#![crate_type="dylib"]
#![feature(quote, plugin_registrar, plugin, rustc_private)]
#![plugin(regex_macros)]
extern crate syntax;
extern crate rustc;
extern crate regex;
extern crate unicode_names;
use syntax::ast;
use syntax::codemap;
use syntax::parse::token;
use syntax::ext::base::{self, ExtCtxt, MacResult, MacEager, DummyResult};
use syntax::ext::build::AstBuilder;
use rustc::plugin::Registry;
#[plugin_registrar]
#[doc(hidden)]
pub fn plugin_registrar(registrar: &mut Registry) {
registrar.register_macro("named_char", named_char);
registrar.register_macro("named", named);
}
fn named_char(cx: &mut ExtCtxt, sp: codemap::Span,
tts: &[ast::TokenTree]) -> Box<MacResult+'static> {
match base::get_single_str_from_tts(cx, sp, tts, "named_char") {
None => {}
Some(name) => match unicode_names::character(&name) {
None => cx.span_err(sp, &format!("`{}` does not name a character", name)),
// everything worked!
Some(c) => return MacEager::expr(cx.expr_lit(sp, ast::LitChar(c))),
}
}
// failed :(
DummyResult::expr(sp)
}
fn | (cx: &mut ExtCtxt, sp: codemap::Span, tts: &[ast::TokenTree]) -> Box<MacResult+'static> {
let string = match base::get_single_str_from_tts(cx, sp, tts, "named") {
None => return DummyResult::expr(sp),
Some(s) => s
};
// make sure unclosed braces don't escape.
static NAMES: regex::Regex = regex!(r"\\N\{(.*?)(?:\}|$)");
let new = NAMES.replace_all(&string, |c: ®ex::Captures| {
let full = c.at(0).unwrap();
if!full.ends_with("}") {
cx.span_err(sp, &format!("unclosed escape in `named!`: {}", full));
} else {
let name = c.at(1).unwrap();
match unicode_names::character(name) {
Some(c) => return c.to_string(),
None => {
cx.span_err(sp, &format!("`{}` does not name a character", name));
}
}
}
// failed :(
String::new()
});
MacEager::expr(cx.expr_str(sp, token::intern_and_get_ident(&new)))
}
| named | identifier_name |
lib.rs | //! A macro that maps unicode names to chars and strings.
#![crate_type="dylib"]
#![feature(quote, plugin_registrar, plugin, rustc_private)]
#![plugin(regex_macros)]
extern crate syntax;
extern crate rustc;
extern crate regex;
extern crate unicode_names;
use syntax::ast;
use syntax::codemap;
use syntax::parse::token;
use syntax::ext::base::{self, ExtCtxt, MacResult, MacEager, DummyResult};
use syntax::ext::build::AstBuilder;
use rustc::plugin::Registry;
#[plugin_registrar]
#[doc(hidden)]
pub fn plugin_registrar(registrar: &mut Registry) {
registrar.register_macro("named_char", named_char);
registrar.register_macro("named", named);
}
fn named_char(cx: &mut ExtCtxt, sp: codemap::Span,
tts: &[ast::TokenTree]) -> Box<MacResult+'static> {
match base::get_single_str_from_tts(cx, sp, tts, "named_char") {
None => {}
Some(name) => match unicode_names::character(&name) {
None => cx.span_err(sp, &format!("`{}` does not name a character", name)),
// everything worked!
Some(c) => return MacEager::expr(cx.expr_lit(sp, ast::LitChar(c))),
}
}
// failed :(
DummyResult::expr(sp)
}
fn named(cx: &mut ExtCtxt, sp: codemap::Span, tts: &[ast::TokenTree]) -> Box<MacResult+'static> {
let string = match base::get_single_str_from_tts(cx, sp, tts, "named") {
None => return DummyResult::expr(sp),
Some(s) => s
};
// make sure unclosed braces don't escape.
static NAMES: regex::Regex = regex!(r"\\N\{(.*?)(?:\}|$)");
| let new = NAMES.replace_all(&string, |c: ®ex::Captures| {
let full = c.at(0).unwrap();
if!full.ends_with("}") {
cx.span_err(sp, &format!("unclosed escape in `named!`: {}", full));
} else {
let name = c.at(1).unwrap();
match unicode_names::character(name) {
Some(c) => return c.to_string(),
None => {
cx.span_err(sp, &format!("`{}` does not name a character", name));
}
}
}
// failed :(
String::new()
});
MacEager::expr(cx.expr_str(sp, token::intern_and_get_ident(&new)))
} | random_line_split |
|
lib.rs | //! A macro that maps unicode names to chars and strings.
#![crate_type="dylib"]
#![feature(quote, plugin_registrar, plugin, rustc_private)]
#![plugin(regex_macros)]
extern crate syntax;
extern crate rustc;
extern crate regex;
extern crate unicode_names;
use syntax::ast;
use syntax::codemap;
use syntax::parse::token;
use syntax::ext::base::{self, ExtCtxt, MacResult, MacEager, DummyResult};
use syntax::ext::build::AstBuilder;
use rustc::plugin::Registry;
#[plugin_registrar]
#[doc(hidden)]
pub fn plugin_registrar(registrar: &mut Registry) |
fn named_char(cx: &mut ExtCtxt, sp: codemap::Span,
tts: &[ast::TokenTree]) -> Box<MacResult+'static> {
match base::get_single_str_from_tts(cx, sp, tts, "named_char") {
None => {}
Some(name) => match unicode_names::character(&name) {
None => cx.span_err(sp, &format!("`{}` does not name a character", name)),
// everything worked!
Some(c) => return MacEager::expr(cx.expr_lit(sp, ast::LitChar(c))),
}
}
// failed :(
DummyResult::expr(sp)
}
fn named(cx: &mut ExtCtxt, sp: codemap::Span, tts: &[ast::TokenTree]) -> Box<MacResult+'static> {
let string = match base::get_single_str_from_tts(cx, sp, tts, "named") {
None => return DummyResult::expr(sp),
Some(s) => s
};
// make sure unclosed braces don't escape.
static NAMES: regex::Regex = regex!(r"\\N\{(.*?)(?:\}|$)");
let new = NAMES.replace_all(&string, |c: ®ex::Captures| {
let full = c.at(0).unwrap();
if!full.ends_with("}") {
cx.span_err(sp, &format!("unclosed escape in `named!`: {}", full));
} else {
let name = c.at(1).unwrap();
match unicode_names::character(name) {
Some(c) => return c.to_string(),
None => {
cx.span_err(sp, &format!("`{}` does not name a character", name));
}
}
}
// failed :(
String::new()
});
MacEager::expr(cx.expr_str(sp, token::intern_and_get_ident(&new)))
}
| {
registrar.register_macro("named_char", named_char);
registrar.register_macro("named", named);
} | identifier_body |
lib.rs | //! A macro that maps unicode names to chars and strings.
#![crate_type="dylib"]
#![feature(quote, plugin_registrar, plugin, rustc_private)]
#![plugin(regex_macros)]
extern crate syntax;
extern crate rustc;
extern crate regex;
extern crate unicode_names;
use syntax::ast;
use syntax::codemap;
use syntax::parse::token;
use syntax::ext::base::{self, ExtCtxt, MacResult, MacEager, DummyResult};
use syntax::ext::build::AstBuilder;
use rustc::plugin::Registry;
#[plugin_registrar]
#[doc(hidden)]
pub fn plugin_registrar(registrar: &mut Registry) {
registrar.register_macro("named_char", named_char);
registrar.register_macro("named", named);
}
fn named_char(cx: &mut ExtCtxt, sp: codemap::Span,
tts: &[ast::TokenTree]) -> Box<MacResult+'static> {
match base::get_single_str_from_tts(cx, sp, tts, "named_char") {
None => {}
Some(name) => match unicode_names::character(&name) {
None => cx.span_err(sp, &format!("`{}` does not name a character", name)),
// everything worked!
Some(c) => return MacEager::expr(cx.expr_lit(sp, ast::LitChar(c))),
}
}
// failed :(
DummyResult::expr(sp)
}
fn named(cx: &mut ExtCtxt, sp: codemap::Span, tts: &[ast::TokenTree]) -> Box<MacResult+'static> {
let string = match base::get_single_str_from_tts(cx, sp, tts, "named") {
None => return DummyResult::expr(sp),
Some(s) => s
};
// make sure unclosed braces don't escape.
static NAMES: regex::Regex = regex!(r"\\N\{(.*?)(?:\}|$)");
let new = NAMES.replace_all(&string, |c: ®ex::Captures| {
let full = c.at(0).unwrap();
if!full.ends_with("}") {
cx.span_err(sp, &format!("unclosed escape in `named!`: {}", full));
} else {
let name = c.at(1).unwrap();
match unicode_names::character(name) {
Some(c) => return c.to_string(),
None => |
}
}
// failed :(
String::new()
});
MacEager::expr(cx.expr_str(sp, token::intern_and_get_ident(&new)))
}
| {
cx.span_err(sp, &format!("`{}` does not name a character", name));
} | conditional_block |
content_encoding.rs | use brotli::enc::backward_references::{BrotliEncoderParams, BrotliEncoderMode};
use brotli::enc::BrotliCompress as brotli_compress;
use flate2::write::{DeflateEncoder, GzEncoder};
use flate2::Compression as Flate2Compression;
use iron::headers::{QualityItem, Encoding};
use bzip2::Compression as BzCompression;
use std::collections::BTreeSet;
use bzip2::write::BzEncoder;
use std::io::{self, Write};
use unicase::UniCase;
use std::path::Path;
use std::fs::File;
use blake3;
lazy_static! {
/// The list of content encodings we handle.
pub static ref SUPPORTED_ENCODINGS: Vec<Encoding> = {
let es = vec![Encoding::Gzip, Encoding::Deflate, Encoding::EncodingExt("br".to_string()), Encoding::EncodingExt("bzip2".to_string())];
[es.clone(), es.into_iter().map(|e| Encoding::EncodingExt(format!("x-{}", e))).collect()].iter().flat_map(|e| e.clone()).collect()
};
/// The list of extensions not to encode.
pub static ref BLACKLISTED_ENCODING_EXTENSIONS: BTreeSet<UniCase<&'static str>> = {
let raw = include_str!("../../assets/encoding_blacklist");
raw.split('\n').map(str::trim).filter(|s|!s.is_empty() &&!s.starts_with('#')).map(UniCase::new).collect()
};
pub static ref BROTLI_PARAMS: BrotliEncoderParams = BrotliEncoderParams {
mode: BrotliEncoderMode::BROTLI_MODE_TEXT,
..Default::default()
};
}
/// The minimal size at which to encode filesystem files.
pub const MIN_ENCODING_SIZE: u64 = 1024;
/// The maximal size at which to encode filesystem files.
pub const MAX_ENCODING_SIZE: u64 = 100 * 1024 * 1024;
/// The minimal size gain at which to preserve encoded filesystem files.
pub const MIN_ENCODING_GAIN: f64 = 1.1;
/// Find best supported encoding to use, or `None` for identity.
pub fn | (requested: &mut [QualityItem<Encoding>]) -> Option<Encoding> {
requested.sort_by_key(|e| e.quality);
requested.iter().filter(|e| e.quality.0!= 0).find(|e| SUPPORTED_ENCODINGS.contains(&e.item)).map(|e| e.item.clone())
}
/// Encode a string slice using a specified encoding or `None` if encoding failed or is not recognised.
pub fn encode_str(dt: &str, enc: &Encoding) -> Option<Vec<u8>> {
type EncodeT = fn(&str) -> Option<Vec<u8>>;
const STR_ENCODING_FNS: &[EncodeT] = &[encode_str_gzip, encode_str_deflate, encode_str_brotli, encode_str_bzip2];
encoding_idx(enc).and_then(|fi| STR_ENCODING_FNS[fi](dt))
}
/// Encode the file denoted by the specified path into the file denoted by the specified path using a specified encoding or
/// `false` if encoding failed, is not recognised or an I/O error occurred.
pub fn encode_file(p: &Path, op: &Path, enc: &Encoding) -> bool {
type EncodeT = fn(File, File) -> bool;
const FILE_ENCODING_FNS: &[EncodeT] = &[encode_file_gzip, encode_file_deflate, encode_file_brotli, encode_file_bzip2];
encoding_idx(enc)
.map(|fi| {
let inf = File::open(p);
let outf = File::create(op);
inf.is_ok() && outf.is_ok() && FILE_ENCODING_FNS[fi](inf.unwrap(), outf.unwrap())
})
.unwrap()
}
/// Encoding extension to use for encoded files, for example "gz" for gzip, or `None` if the encoding is not recognised.
pub fn encoding_extension(enc: &Encoding) -> Option<&'static str> {
const ENCODING_EXTS: &[&str] = &["gz", "dflt", "br", "bz2"];
encoding_idx(enc).map(|ei| ENCODING_EXTS[ei])
}
/// Return the 256-bit BLAKE3 hash of the file denoted by the specified path.
pub fn file_hash(p: &Path) -> blake3::Hash {
let mut ctx = blake3::Hasher::new();
io::copy(&mut File::open(p).unwrap(), &mut ctx).unwrap();
ctx.finalize()
}
fn encoding_idx(enc: &Encoding) -> Option<usize> {
match *enc {
Encoding::Gzip => Some(0),
Encoding::Deflate => Some(1),
Encoding::EncodingExt(ref e) => {
match &e[..] {
"x-gzip" => Some(0),
"x-deflate" => Some(1),
"br" | "x-br" => Some(2),
"bzip2" | "x-bzip2" => Some(3),
_ => None,
}
}
_ => None,
}
}
macro_rules! encode_fn {
($str_fn_name:ident, $file_fn_name:ident, $enc_tp:ident, $comp_lvl:expr, $constructor:expr) => {
fn $str_fn_name(dt: &str) -> Option<Vec<u8>> {
let mut cmp = $constructor(Vec::new());
cmp.write_all(dt.as_bytes()).ok().and_then(|_| cmp.finish().ok())
}
fn $file_fn_name(mut inf: File, outf: File) -> bool {
let mut cmp = $constructor(outf);
io::copy(&mut inf, &mut cmp).and_then(|_| cmp.finish()).is_ok()
}
};
($str_fn_name:ident, $file_fn_name:ident, $enc_tp:ident, $comp_lvl:expr) => {
encode_fn!($str_fn_name, $file_fn_name, $enc_tp, $comp_lvl, |into| $enc_tp::new(into, $comp_lvl));
}
}
encode_fn!(encode_str_gzip, encode_file_gzip, GzEncoder, Flate2Compression::default());
encode_fn!(encode_str_deflate, encode_file_deflate, DeflateEncoder, Flate2Compression::default());
encode_fn!(encode_str_bzip2, encode_file_bzip2, BzEncoder, BzCompression::Default);
fn encode_str_brotli(dt: &str) -> Option<Vec<u8>> {
let mut ret = Vec::new();
brotli_compress(&mut dt.as_bytes(), &mut ret, &BROTLI_PARAMS).ok().map(|_| ret)
}
fn encode_file_brotli(mut inf: File, mut outf: File) -> bool {
brotli_compress(&mut inf, &mut outf, &BROTLI_PARAMS).is_ok()
}
| response_encoding | identifier_name |
content_encoding.rs | use brotli::enc::backward_references::{BrotliEncoderParams, BrotliEncoderMode};
use brotli::enc::BrotliCompress as brotli_compress;
use flate2::write::{DeflateEncoder, GzEncoder};
use flate2::Compression as Flate2Compression;
use iron::headers::{QualityItem, Encoding};
use bzip2::Compression as BzCompression;
use std::collections::BTreeSet;
use bzip2::write::BzEncoder;
use std::io::{self, Write};
use unicase::UniCase;
use std::path::Path;
use std::fs::File;
use blake3;
lazy_static! {
/// The list of content encodings we handle.
pub static ref SUPPORTED_ENCODINGS: Vec<Encoding> = {
let es = vec![Encoding::Gzip, Encoding::Deflate, Encoding::EncodingExt("br".to_string()), Encoding::EncodingExt("bzip2".to_string())];
[es.clone(), es.into_iter().map(|e| Encoding::EncodingExt(format!("x-{}", e))).collect()].iter().flat_map(|e| e.clone()).collect()
};
/// The list of extensions not to encode.
pub static ref BLACKLISTED_ENCODING_EXTENSIONS: BTreeSet<UniCase<&'static str>> = {
let raw = include_str!("../../assets/encoding_blacklist");
raw.split('\n').map(str::trim).filter(|s|!s.is_empty() &&!s.starts_with('#')).map(UniCase::new).collect()
};
pub static ref BROTLI_PARAMS: BrotliEncoderParams = BrotliEncoderParams {
mode: BrotliEncoderMode::BROTLI_MODE_TEXT,
..Default::default()
};
}
/// The minimal size at which to encode filesystem files.
pub const MIN_ENCODING_SIZE: u64 = 1024;
/// The maximal size at which to encode filesystem files. |
/// Find best supported encoding to use, or `None` for identity.
pub fn response_encoding(requested: &mut [QualityItem<Encoding>]) -> Option<Encoding> {
requested.sort_by_key(|e| e.quality);
requested.iter().filter(|e| e.quality.0!= 0).find(|e| SUPPORTED_ENCODINGS.contains(&e.item)).map(|e| e.item.clone())
}
/// Encode a string slice using a specified encoding or `None` if encoding failed or is not recognised.
pub fn encode_str(dt: &str, enc: &Encoding) -> Option<Vec<u8>> {
type EncodeT = fn(&str) -> Option<Vec<u8>>;
const STR_ENCODING_FNS: &[EncodeT] = &[encode_str_gzip, encode_str_deflate, encode_str_brotli, encode_str_bzip2];
encoding_idx(enc).and_then(|fi| STR_ENCODING_FNS[fi](dt))
}
/// Encode the file denoted by the specified path into the file denoted by the specified path using a specified encoding or
/// `false` if encoding failed, is not recognised or an I/O error occurred.
pub fn encode_file(p: &Path, op: &Path, enc: &Encoding) -> bool {
type EncodeT = fn(File, File) -> bool;
const FILE_ENCODING_FNS: &[EncodeT] = &[encode_file_gzip, encode_file_deflate, encode_file_brotli, encode_file_bzip2];
encoding_idx(enc)
.map(|fi| {
let inf = File::open(p);
let outf = File::create(op);
inf.is_ok() && outf.is_ok() && FILE_ENCODING_FNS[fi](inf.unwrap(), outf.unwrap())
})
.unwrap()
}
/// Encoding extension to use for encoded files, for example "gz" for gzip, or `None` if the encoding is not recognised.
pub fn encoding_extension(enc: &Encoding) -> Option<&'static str> {
const ENCODING_EXTS: &[&str] = &["gz", "dflt", "br", "bz2"];
encoding_idx(enc).map(|ei| ENCODING_EXTS[ei])
}
/// Return the 256-bit BLAKE3 hash of the file denoted by the specified path.
pub fn file_hash(p: &Path) -> blake3::Hash {
let mut ctx = blake3::Hasher::new();
io::copy(&mut File::open(p).unwrap(), &mut ctx).unwrap();
ctx.finalize()
}
fn encoding_idx(enc: &Encoding) -> Option<usize> {
match *enc {
Encoding::Gzip => Some(0),
Encoding::Deflate => Some(1),
Encoding::EncodingExt(ref e) => {
match &e[..] {
"x-gzip" => Some(0),
"x-deflate" => Some(1),
"br" | "x-br" => Some(2),
"bzip2" | "x-bzip2" => Some(3),
_ => None,
}
}
_ => None,
}
}
macro_rules! encode_fn {
($str_fn_name:ident, $file_fn_name:ident, $enc_tp:ident, $comp_lvl:expr, $constructor:expr) => {
fn $str_fn_name(dt: &str) -> Option<Vec<u8>> {
let mut cmp = $constructor(Vec::new());
cmp.write_all(dt.as_bytes()).ok().and_then(|_| cmp.finish().ok())
}
fn $file_fn_name(mut inf: File, outf: File) -> bool {
let mut cmp = $constructor(outf);
io::copy(&mut inf, &mut cmp).and_then(|_| cmp.finish()).is_ok()
}
};
($str_fn_name:ident, $file_fn_name:ident, $enc_tp:ident, $comp_lvl:expr) => {
encode_fn!($str_fn_name, $file_fn_name, $enc_tp, $comp_lvl, |into| $enc_tp::new(into, $comp_lvl));
}
}
encode_fn!(encode_str_gzip, encode_file_gzip, GzEncoder, Flate2Compression::default());
encode_fn!(encode_str_deflate, encode_file_deflate, DeflateEncoder, Flate2Compression::default());
encode_fn!(encode_str_bzip2, encode_file_bzip2, BzEncoder, BzCompression::Default);
fn encode_str_brotli(dt: &str) -> Option<Vec<u8>> {
let mut ret = Vec::new();
brotli_compress(&mut dt.as_bytes(), &mut ret, &BROTLI_PARAMS).ok().map(|_| ret)
}
fn encode_file_brotli(mut inf: File, mut outf: File) -> bool {
brotli_compress(&mut inf, &mut outf, &BROTLI_PARAMS).is_ok()
} | pub const MAX_ENCODING_SIZE: u64 = 100 * 1024 * 1024;
/// The minimal size gain at which to preserve encoded filesystem files.
pub const MIN_ENCODING_GAIN: f64 = 1.1;
| random_line_split |
content_encoding.rs | use brotli::enc::backward_references::{BrotliEncoderParams, BrotliEncoderMode};
use brotli::enc::BrotliCompress as brotli_compress;
use flate2::write::{DeflateEncoder, GzEncoder};
use flate2::Compression as Flate2Compression;
use iron::headers::{QualityItem, Encoding};
use bzip2::Compression as BzCompression;
use std::collections::BTreeSet;
use bzip2::write::BzEncoder;
use std::io::{self, Write};
use unicase::UniCase;
use std::path::Path;
use std::fs::File;
use blake3;
lazy_static! {
/// The list of content encodings we handle.
pub static ref SUPPORTED_ENCODINGS: Vec<Encoding> = {
let es = vec![Encoding::Gzip, Encoding::Deflate, Encoding::EncodingExt("br".to_string()), Encoding::EncodingExt("bzip2".to_string())];
[es.clone(), es.into_iter().map(|e| Encoding::EncodingExt(format!("x-{}", e))).collect()].iter().flat_map(|e| e.clone()).collect()
};
/// The list of extensions not to encode.
pub static ref BLACKLISTED_ENCODING_EXTENSIONS: BTreeSet<UniCase<&'static str>> = {
let raw = include_str!("../../assets/encoding_blacklist");
raw.split('\n').map(str::trim).filter(|s|!s.is_empty() &&!s.starts_with('#')).map(UniCase::new).collect()
};
pub static ref BROTLI_PARAMS: BrotliEncoderParams = BrotliEncoderParams {
mode: BrotliEncoderMode::BROTLI_MODE_TEXT,
..Default::default()
};
}
/// The minimal size at which to encode filesystem files.
pub const MIN_ENCODING_SIZE: u64 = 1024;
/// The maximal size at which to encode filesystem files.
pub const MAX_ENCODING_SIZE: u64 = 100 * 1024 * 1024;
/// The minimal size gain at which to preserve encoded filesystem files.
pub const MIN_ENCODING_GAIN: f64 = 1.1;
/// Find best supported encoding to use, or `None` for identity.
pub fn response_encoding(requested: &mut [QualityItem<Encoding>]) -> Option<Encoding> {
requested.sort_by_key(|e| e.quality);
requested.iter().filter(|e| e.quality.0!= 0).find(|e| SUPPORTED_ENCODINGS.contains(&e.item)).map(|e| e.item.clone())
}
/// Encode a string slice using a specified encoding or `None` if encoding failed or is not recognised.
pub fn encode_str(dt: &str, enc: &Encoding) -> Option<Vec<u8>> {
type EncodeT = fn(&str) -> Option<Vec<u8>>;
const STR_ENCODING_FNS: &[EncodeT] = &[encode_str_gzip, encode_str_deflate, encode_str_brotli, encode_str_bzip2];
encoding_idx(enc).and_then(|fi| STR_ENCODING_FNS[fi](dt))
}
/// Encode the file denoted by the specified path into the file denoted by the specified path using a specified encoding or
/// `false` if encoding failed, is not recognised or an I/O error occurred.
pub fn encode_file(p: &Path, op: &Path, enc: &Encoding) -> bool {
type EncodeT = fn(File, File) -> bool;
const FILE_ENCODING_FNS: &[EncodeT] = &[encode_file_gzip, encode_file_deflate, encode_file_brotli, encode_file_bzip2];
encoding_idx(enc)
.map(|fi| {
let inf = File::open(p);
let outf = File::create(op);
inf.is_ok() && outf.is_ok() && FILE_ENCODING_FNS[fi](inf.unwrap(), outf.unwrap())
})
.unwrap()
}
/// Encoding extension to use for encoded files, for example "gz" for gzip, or `None` if the encoding is not recognised.
pub fn encoding_extension(enc: &Encoding) -> Option<&'static str> {
const ENCODING_EXTS: &[&str] = &["gz", "dflt", "br", "bz2"];
encoding_idx(enc).map(|ei| ENCODING_EXTS[ei])
}
/// Return the 256-bit BLAKE3 hash of the file denoted by the specified path.
pub fn file_hash(p: &Path) -> blake3::Hash {
let mut ctx = blake3::Hasher::new();
io::copy(&mut File::open(p).unwrap(), &mut ctx).unwrap();
ctx.finalize()
}
fn encoding_idx(enc: &Encoding) -> Option<usize> {
match *enc {
Encoding::Gzip => Some(0),
Encoding::Deflate => Some(1),
Encoding::EncodingExt(ref e) => {
match &e[..] {
"x-gzip" => Some(0),
"x-deflate" => Some(1),
"br" | "x-br" => Some(2),
"bzip2" | "x-bzip2" => Some(3),
_ => None,
}
}
_ => None,
}
}
macro_rules! encode_fn {
($str_fn_name:ident, $file_fn_name:ident, $enc_tp:ident, $comp_lvl:expr, $constructor:expr) => {
fn $str_fn_name(dt: &str) -> Option<Vec<u8>> {
let mut cmp = $constructor(Vec::new());
cmp.write_all(dt.as_bytes()).ok().and_then(|_| cmp.finish().ok())
}
fn $file_fn_name(mut inf: File, outf: File) -> bool {
let mut cmp = $constructor(outf);
io::copy(&mut inf, &mut cmp).and_then(|_| cmp.finish()).is_ok()
}
};
($str_fn_name:ident, $file_fn_name:ident, $enc_tp:ident, $comp_lvl:expr) => {
encode_fn!($str_fn_name, $file_fn_name, $enc_tp, $comp_lvl, |into| $enc_tp::new(into, $comp_lvl));
}
}
encode_fn!(encode_str_gzip, encode_file_gzip, GzEncoder, Flate2Compression::default());
encode_fn!(encode_str_deflate, encode_file_deflate, DeflateEncoder, Flate2Compression::default());
encode_fn!(encode_str_bzip2, encode_file_bzip2, BzEncoder, BzCompression::Default);
fn encode_str_brotli(dt: &str) -> Option<Vec<u8>> {
let mut ret = Vec::new();
brotli_compress(&mut dt.as_bytes(), &mut ret, &BROTLI_PARAMS).ok().map(|_| ret)
}
fn encode_file_brotli(mut inf: File, mut outf: File) -> bool | {
brotli_compress(&mut inf, &mut outf, &BROTLI_PARAMS).is_ok()
} | identifier_body |
|
lex-bad-char-literals.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
static c: char =
'\u539_' //~ ERROR: illegal character in numeric character escape
;
static c2: char =
'\Uffffffff' //~ ERROR: illegal numeric character escape
;
static c3: char =
'\x1' //~ ERROR: numeric character escape is too short
;
static c4: char =
'\u23q' //~ ERROR: illegal character in numeric character escape
;
//~^^ ERROR: numeric character escape is too short
static s: &'static str =
"\x1" //~ ERROR: numeric character escape is too short | ;
static c: char =
'\●' //~ ERROR: unknown character escape
;
static s: &'static str =
"\●" //~ ERROR: unknown character escape
;
// THIS MUST BE LAST, since unterminated character constants kill the lexer
static c: char =
'● //~ ERROR: unterminated character constant
; | ;
static s2: &'static str =
"\u23q" //~ ERROR: illegal character in numeric character escape
//~^ ERROR: numeric character escape is too short | random_line_split |
lib.rs | // Copyright 2019 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//! Support crate for writing fuzzers in Chrome OS.
//!
//! The major features provided by this crate are:
//!
//! * The [`fuzz_target`] macro which wraps the body of the fuzzing code with
//! all with all the boilerplate needed to build and run it as a fuzzer on
//! Chrome OS infrastructure.
//! * The [`FuzzRng`] type that provides a random number generator using fuzzer
//! input as the source of its randomness. Fuzzers that need to generate
//! structured data can use this type in conjunction with the [`rand`] crate
//! to generate the data they need.
//!
//! # Getting Started
//!
//! To use this crate add it as a dependency to the fuzzer's `Cargo.toml` along
//! with the crate to be fuzzed:
//!
//! ```Cargo.toml
//! [dependencies]
//! cros_fuzz = "*"
//! your_crate = "*"
//! ```
//!
//! Then use the [`fuzz_target`] macro to write the body of the fuzzer. All
//! fuzzers should use the `#![no_main]` crate attribute as the main function
//! will be provided by the fuzzer runtime.
//!
//! ```rust,ignore
//! #![no_main]
//!
//! use cros_fuzz::fuzz_target;
//! use your_crate::some_function;
//!
//! fuzz_target!(|data: &[u8]| {
//! some_function(data);
//! });
//! ```
//!
//! [`FuzzRng`]: rand/struct.FuzzRng.html
//! [`fuzz_target`]: macro.fuzz_target.html
//! [`rand`]: https://docs.rs/rand
pub mod rand;
/// The main macro for writing a fuzzer. The fuzzer runtime will repeatedly
/// call the body of `fuzz_target!` with a slice of pseudo-random bytes, until
/// your program hits an error condition (segfault, panic, etc). | ///
/// # Examples
///
/// ```
/// use std::str;
/// # #[macro_use] extern crate cros_fuzz;
///
/// fuzz_target!(|data: &[u8]| {
/// let _ = str::from_utf8(data);
/// });
///
/// # fn main() {
/// # let buf = b"hello, world!";
/// # llvm_fuzzer_test_one_input(buf.as_ptr(), buf.len());
/// # }
/// ```
#[macro_export]
macro_rules! fuzz_target {
(|$bytes:ident| $body:block) => {
use std::panic;
use std::process;
use std::slice;
#[export_name = "LLVMFuzzerTestOneInput"]
fn llvm_fuzzer_test_one_input(data: *const u8, size: usize) -> i32 {
// We cannot unwind past ffi boundaries.
panic::catch_unwind(|| {
// Safe because the libfuzzer runtime will guarantee that `data` is
// at least `size` bytes long and that it will be valid for the lifetime
// of this function.
let $bytes = unsafe { slice::from_raw_parts(data, size) };
$body
})
.err()
.map(|_| process::abort());
0
}
};
(|$bytes:ident: &[u8]| $body:block) => {
fuzz_target!(|$bytes| $body);
};
} | random_line_split |
|
mod.rs | use crate::types::game::paddock::PaddockInformationsForSell;
use crate::types::game::paddock::PaddockInstancesInformations;
use protocol_derive::{Decode, Encode};
#[derive(Clone, PartialEq, Debug, Encode, Decode)]
#[protocol(id = 5824)]
pub struct PaddockPropertiesMessage<'a> {
pub properties: PaddockInstancesInformations<'a>,
}
#[derive(Clone, PartialEq, Debug, Encode, Decode)]
#[protocol(id = 6141)]
pub struct PaddockToSellListRequestMessage<'a> {
#[protocol(var)]
pub page_index: u16,
pub _phantom: std::marker::PhantomData<&'a ()>,
}
#[derive(Clone, PartialEq, Debug, Encode, Decode)]
#[protocol(id = 6026)]
pub struct GameDataPlayFarmObjectAnimationMessage<'a> {
#[protocol(var_contents)]
pub cell_id: std::borrow::Cow<'a, [u16]>,
}
#[derive(Clone, PartialEq, Debug, Encode, Decode)]
#[protocol(id = 6161)]
pub struct | <'a> {
pub area_id: i32,
pub at_least_nb_mount: i8,
pub at_least_nb_machine: i8,
#[protocol(var)]
pub max_price: u64,
pub order_by: u8,
pub _phantom: std::marker::PhantomData<&'a ()>,
}
#[derive(Clone, PartialEq, Debug, Encode, Decode)]
#[protocol(id = 6018)]
pub struct PaddockSellBuyDialogMessage<'a> {
pub bsell: bool,
#[protocol(var)]
pub owner_id: u32,
#[protocol(var)]
pub price: u64,
pub _phantom: std::marker::PhantomData<&'a ()>,
}
#[derive(Clone, PartialEq, Debug, Encode, Decode)]
#[protocol(id = 6138)]
pub struct PaddockToSellListMessage<'a> {
#[protocol(var)]
pub page_index: u16,
#[protocol(var)]
pub total_page: u16,
pub paddock_list: std::borrow::Cow<'a, [PaddockInformationsForSell<'a>]>,
}
| PaddockToSellFilterMessage | identifier_name |
mod.rs | use crate::types::game::paddock::PaddockInformationsForSell;
use crate::types::game::paddock::PaddockInstancesInformations;
use protocol_derive::{Decode, Encode};
#[derive(Clone, PartialEq, Debug, Encode, Decode)]
#[protocol(id = 5824)]
pub struct PaddockPropertiesMessage<'a> {
pub properties: PaddockInstancesInformations<'a>,
} | #[protocol(var)]
pub page_index: u16,
pub _phantom: std::marker::PhantomData<&'a ()>,
}
#[derive(Clone, PartialEq, Debug, Encode, Decode)]
#[protocol(id = 6026)]
pub struct GameDataPlayFarmObjectAnimationMessage<'a> {
#[protocol(var_contents)]
pub cell_id: std::borrow::Cow<'a, [u16]>,
}
#[derive(Clone, PartialEq, Debug, Encode, Decode)]
#[protocol(id = 6161)]
pub struct PaddockToSellFilterMessage<'a> {
pub area_id: i32,
pub at_least_nb_mount: i8,
pub at_least_nb_machine: i8,
#[protocol(var)]
pub max_price: u64,
pub order_by: u8,
pub _phantom: std::marker::PhantomData<&'a ()>,
}
#[derive(Clone, PartialEq, Debug, Encode, Decode)]
#[protocol(id = 6018)]
pub struct PaddockSellBuyDialogMessage<'a> {
pub bsell: bool,
#[protocol(var)]
pub owner_id: u32,
#[protocol(var)]
pub price: u64,
pub _phantom: std::marker::PhantomData<&'a ()>,
}
#[derive(Clone, PartialEq, Debug, Encode, Decode)]
#[protocol(id = 6138)]
pub struct PaddockToSellListMessage<'a> {
#[protocol(var)]
pub page_index: u16,
#[protocol(var)]
pub total_page: u16,
pub paddock_list: std::borrow::Cow<'a, [PaddockInformationsForSell<'a>]>,
} |
#[derive(Clone, PartialEq, Debug, Encode, Decode)]
#[protocol(id = 6141)]
pub struct PaddockToSellListRequestMessage<'a> { | random_line_split |
lib.rs | // Tifflin OS - Asynchronous common interface
// - By John Hodge (thePowersGang)
//
//
//! Asynchronous waiting support
#[macro_use]
extern crate syscalls;
/// Trait for types that can be used for 'idle_loop'
pub trait WaitController
{
fn get_count(&self) -> usize;
fn populate(&self, cb: &mut FnMut(::syscalls::WaitItem));
fn handle(&mut self, events: &[::syscalls::WaitItem]);
}
/// Idle, handling events on each WaitController passed
pub fn | (items: &mut [&mut WaitController])
{
let mut objects = Vec::new();
loop {
let count = items.iter().fold(0, |sum,ctrlr| sum + ctrlr.get_count());
objects.reserve( count );
for ctrlr in items.iter() {
ctrlr.populate(&mut |wi| objects.push(wi));
}
::syscalls::threads::wait(&mut objects,!0);
let mut ofs = 0;
for ctrlr in items.iter_mut()
{
let num = ctrlr.get_count();
ctrlr.handle( &objects[ofs.. ofs + num] );
ofs += num;
}
objects.clear();
}
}
| idle_loop | identifier_name |
lib.rs | // Tifflin OS - Asynchronous common interface
// - By John Hodge (thePowersGang)
//
//
//! Asynchronous waiting support
#[macro_use]
extern crate syscalls;
/// Trait for types that can be used for 'idle_loop'
pub trait WaitController
{
fn get_count(&self) -> usize;
fn populate(&self, cb: &mut FnMut(::syscalls::WaitItem));
fn handle(&mut self, events: &[::syscalls::WaitItem]);
}
/// Idle, handling events on each WaitController passed
pub fn idle_loop(items: &mut [&mut WaitController]) | let count = items.iter().fold(0, |sum,ctrlr| sum + ctrlr.get_count());
objects.reserve( count );
for ctrlr in items.iter() {
ctrlr.populate(&mut |wi| objects.push(wi));
}
::syscalls::threads::wait(&mut objects,!0);
let mut ofs = 0;
for ctrlr in items.iter_mut()
{
let num = ctrlr.get_count();
ctrlr.handle( &objects[ofs.. ofs + num] );
ofs += num;
}
objects.clear();
}
} | {
let mut objects = Vec::new();
loop { | random_line_split |
lib.rs | // Tifflin OS - Asynchronous common interface
// - By John Hodge (thePowersGang)
//
//
//! Asynchronous waiting support
#[macro_use]
extern crate syscalls;
/// Trait for types that can be used for 'idle_loop'
pub trait WaitController
{
fn get_count(&self) -> usize;
fn populate(&self, cb: &mut FnMut(::syscalls::WaitItem));
fn handle(&mut self, events: &[::syscalls::WaitItem]);
}
/// Idle, handling events on each WaitController passed
pub fn idle_loop(items: &mut [&mut WaitController])
| objects.clear();
}
}
| {
let mut objects = Vec::new();
loop {
let count = items.iter().fold(0, |sum,ctrlr| sum + ctrlr.get_count());
objects.reserve( count );
for ctrlr in items.iter() {
ctrlr.populate(&mut |wi| objects.push(wi));
}
::syscalls::threads::wait(&mut objects, !0);
let mut ofs = 0;
for ctrlr in items.iter_mut()
{
let num = ctrlr.get_count();
ctrlr.handle( &objects[ofs .. ofs + num] );
ofs += num;
}
| identifier_body |
metadata.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! This module contains utilities for outputting metadata for diagnostic errors.
//!
//! Each set of errors is mapped to a metadata file by a name, which is
//! currently always a crate name.
use std::collections::BTreeMap;
use std::path::PathBuf;
use std::fs::{remove_file, create_dir_all, File};
use std::error::Error;
use syntax_pos::Span;
use ext::base::ExtCtxt;
use diagnostics::plugin::{ErrorMap, ErrorInfo};
use serde_json;
// Default metadata directory to use for extended error JSON.
const ERROR_METADATA_PREFIX: &'static str = "tmp/extended-errors";
/// JSON encodable/decodable version of `ErrorInfo`.
#[derive(PartialEq, Deserialize, Serialize)]
pub struct ErrorMetadata {
pub description: Option<String>,
pub use_site: Option<ErrorLocation>
}
/// Mapping from error codes to metadata that can be (de)serialized.
pub type ErrorMetadataMap = BTreeMap<String, ErrorMetadata>;
/// JSON encodable error location type with filename and line number.
#[derive(PartialEq, Deserialize, Serialize)]
pub struct | {
pub filename: String,
pub line: usize
}
impl ErrorLocation {
/// Create an error location from a span.
pub fn from_span(ecx: &ExtCtxt, sp: Span) -> ErrorLocation {
let loc = ecx.codemap().lookup_char_pos_adj(sp.lo);
ErrorLocation {
filename: loc.filename,
line: loc.line
}
}
}
/// Get the directory where metadata for a given `prefix` should be stored.
///
/// See `output_metadata`.
pub fn get_metadata_dir(prefix: &str) -> PathBuf {
PathBuf::from(ERROR_METADATA_PREFIX).join(prefix)
}
/// Map `name` to a path in the given directory: <directory>/<name>.json
fn get_metadata_path(directory: PathBuf, name: &str) -> PathBuf {
directory.join(format!("{}.json", name))
}
/// Write metadata for the errors in `err_map` to disk, to a file corresponding to `prefix/name`.
///
/// For our current purposes the prefix is the target architecture and the name is a crate name.
/// If an error occurs steps will be taken to ensure that no file is created.
pub fn output_metadata(ecx: &ExtCtxt, prefix: &str, name: &str, err_map: &ErrorMap)
-> Result<(), Box<Error>>
{
// Create the directory to place the file in.
let metadata_dir = get_metadata_dir(prefix);
create_dir_all(&metadata_dir)?;
// Open the metadata file.
let metadata_path = get_metadata_path(metadata_dir, name);
let mut metadata_file = File::create(&metadata_path)?;
// Construct a serializable map.
let json_map = err_map.iter().map(|(k, &ErrorInfo { description, use_site })| {
let key = k.as_str().to_string();
let value = ErrorMetadata {
description: description.map(|n| n.as_str().to_string()),
use_site: use_site.map(|sp| ErrorLocation::from_span(ecx, sp))
};
(key, value)
}).collect::<ErrorMetadataMap>();
// Write the data to the file, deleting it if the write fails.
let result = serde_json::to_writer(&mut metadata_file, &json_map);
if result.is_err() {
remove_file(&metadata_path)?;
}
Ok(result?)
}
| ErrorLocation | identifier_name |
metadata.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! This module contains utilities for outputting metadata for diagnostic errors.
//!
//! Each set of errors is mapped to a metadata file by a name, which is
//! currently always a crate name.
use std::collections::BTreeMap;
use std::path::PathBuf;
use std::fs::{remove_file, create_dir_all, File};
use std::error::Error;
use syntax_pos::Span;
use ext::base::ExtCtxt;
use diagnostics::plugin::{ErrorMap, ErrorInfo};
use serde_json;
// Default metadata directory to use for extended error JSON.
const ERROR_METADATA_PREFIX: &'static str = "tmp/extended-errors";
/// JSON encodable/decodable version of `ErrorInfo`.
#[derive(PartialEq, Deserialize, Serialize)]
pub struct ErrorMetadata {
pub description: Option<String>,
pub use_site: Option<ErrorLocation>
}
/// Mapping from error codes to metadata that can be (de)serialized.
pub type ErrorMetadataMap = BTreeMap<String, ErrorMetadata>;
/// JSON encodable error location type with filename and line number.
#[derive(PartialEq, Deserialize, Serialize)]
pub struct ErrorLocation {
pub filename: String,
pub line: usize
}
impl ErrorLocation {
/// Create an error location from a span.
pub fn from_span(ecx: &ExtCtxt, sp: Span) -> ErrorLocation {
let loc = ecx.codemap().lookup_char_pos_adj(sp.lo);
ErrorLocation {
filename: loc.filename,
line: loc.line
}
}
}
/// Get the directory where metadata for a given `prefix` should be stored.
///
/// See `output_metadata`.
pub fn get_metadata_dir(prefix: &str) -> PathBuf {
PathBuf::from(ERROR_METADATA_PREFIX).join(prefix)
}
/// Map `name` to a path in the given directory: <directory>/<name>.json
fn get_metadata_path(directory: PathBuf, name: &str) -> PathBuf |
/// Write metadata for the errors in `err_map` to disk, to a file corresponding to `prefix/name`.
///
/// For our current purposes the prefix is the target architecture and the name is a crate name.
/// If an error occurs steps will be taken to ensure that no file is created.
pub fn output_metadata(ecx: &ExtCtxt, prefix: &str, name: &str, err_map: &ErrorMap)
-> Result<(), Box<Error>>
{
// Create the directory to place the file in.
let metadata_dir = get_metadata_dir(prefix);
create_dir_all(&metadata_dir)?;
// Open the metadata file.
let metadata_path = get_metadata_path(metadata_dir, name);
let mut metadata_file = File::create(&metadata_path)?;
// Construct a serializable map.
let json_map = err_map.iter().map(|(k, &ErrorInfo { description, use_site })| {
let key = k.as_str().to_string();
let value = ErrorMetadata {
description: description.map(|n| n.as_str().to_string()),
use_site: use_site.map(|sp| ErrorLocation::from_span(ecx, sp))
};
(key, value)
}).collect::<ErrorMetadataMap>();
// Write the data to the file, deleting it if the write fails.
let result = serde_json::to_writer(&mut metadata_file, &json_map);
if result.is_err() {
remove_file(&metadata_path)?;
}
Ok(result?)
}
| {
directory.join(format!("{}.json", name))
} | identifier_body |
metadata.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! This module contains utilities for outputting metadata for diagnostic errors.
//!
//! Each set of errors is mapped to a metadata file by a name, which is
//! currently always a crate name.
use std::collections::BTreeMap;
use std::path::PathBuf;
use std::fs::{remove_file, create_dir_all, File};
use std::error::Error;
use syntax_pos::Span;
use ext::base::ExtCtxt;
use diagnostics::plugin::{ErrorMap, ErrorInfo};
use serde_json;
// Default metadata directory to use for extended error JSON.
const ERROR_METADATA_PREFIX: &'static str = "tmp/extended-errors";
/// JSON encodable/decodable version of `ErrorInfo`.
#[derive(PartialEq, Deserialize, Serialize)]
pub struct ErrorMetadata {
pub description: Option<String>,
pub use_site: Option<ErrorLocation>
}
/// Mapping from error codes to metadata that can be (de)serialized.
pub type ErrorMetadataMap = BTreeMap<String, ErrorMetadata>;
/// JSON encodable error location type with filename and line number.
#[derive(PartialEq, Deserialize, Serialize)]
pub struct ErrorLocation {
pub filename: String,
pub line: usize
}
impl ErrorLocation {
/// Create an error location from a span.
pub fn from_span(ecx: &ExtCtxt, sp: Span) -> ErrorLocation {
let loc = ecx.codemap().lookup_char_pos_adj(sp.lo);
ErrorLocation {
filename: loc.filename,
line: loc.line
}
}
}
/// Get the directory where metadata for a given `prefix` should be stored.
///
/// See `output_metadata`.
pub fn get_metadata_dir(prefix: &str) -> PathBuf {
PathBuf::from(ERROR_METADATA_PREFIX).join(prefix)
}
/// Map `name` to a path in the given directory: <directory>/<name>.json
fn get_metadata_path(directory: PathBuf, name: &str) -> PathBuf {
directory.join(format!("{}.json", name))
}
/// Write metadata for the errors in `err_map` to disk, to a file corresponding to `prefix/name`.
///
/// For our current purposes the prefix is the target architecture and the name is a crate name.
/// If an error occurs steps will be taken to ensure that no file is created.
pub fn output_metadata(ecx: &ExtCtxt, prefix: &str, name: &str, err_map: &ErrorMap)
-> Result<(), Box<Error>>
{
// Create the directory to place the file in.
let metadata_dir = get_metadata_dir(prefix);
create_dir_all(&metadata_dir)?;
// Open the metadata file.
let metadata_path = get_metadata_path(metadata_dir, name);
let mut metadata_file = File::create(&metadata_path)?;
// Construct a serializable map.
let json_map = err_map.iter().map(|(k, &ErrorInfo { description, use_site })| {
let key = k.as_str().to_string();
let value = ErrorMetadata {
description: description.map(|n| n.as_str().to_string()),
use_site: use_site.map(|sp| ErrorLocation::from_span(ecx, sp))
};
(key, value)
}).collect::<ErrorMetadataMap>();
// Write the data to the file, deleting it if the write fails.
let result = serde_json::to_writer(&mut metadata_file, &json_map);
if result.is_err() |
Ok(result?)
}
| {
remove_file(&metadata_path)?;
} | conditional_block |
metadata.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! This module contains utilities for outputting metadata for diagnostic errors.
//!
//! Each set of errors is mapped to a metadata file by a name, which is
//! currently always a crate name.
use std::collections::BTreeMap;
use std::path::PathBuf;
use std::fs::{remove_file, create_dir_all, File};
use std::error::Error;
use syntax_pos::Span;
use ext::base::ExtCtxt;
use diagnostics::plugin::{ErrorMap, ErrorInfo};
use serde_json;
// Default metadata directory to use for extended error JSON.
const ERROR_METADATA_PREFIX: &'static str = "tmp/extended-errors";
/// JSON encodable/decodable version of `ErrorInfo`.
#[derive(PartialEq, Deserialize, Serialize)]
pub struct ErrorMetadata {
pub description: Option<String>,
pub use_site: Option<ErrorLocation>
}
/// Mapping from error codes to metadata that can be (de)serialized.
pub type ErrorMetadataMap = BTreeMap<String, ErrorMetadata>;
| pub struct ErrorLocation {
pub filename: String,
pub line: usize
}
impl ErrorLocation {
/// Create an error location from a span.
pub fn from_span(ecx: &ExtCtxt, sp: Span) -> ErrorLocation {
let loc = ecx.codemap().lookup_char_pos_adj(sp.lo);
ErrorLocation {
filename: loc.filename,
line: loc.line
}
}
}
/// Get the directory where metadata for a given `prefix` should be stored.
///
/// See `output_metadata`.
pub fn get_metadata_dir(prefix: &str) -> PathBuf {
PathBuf::from(ERROR_METADATA_PREFIX).join(prefix)
}
/// Map `name` to a path in the given directory: <directory>/<name>.json
fn get_metadata_path(directory: PathBuf, name: &str) -> PathBuf {
directory.join(format!("{}.json", name))
}
/// Write metadata for the errors in `err_map` to disk, to a file corresponding to `prefix/name`.
///
/// For our current purposes the prefix is the target architecture and the name is a crate name.
/// If an error occurs steps will be taken to ensure that no file is created.
pub fn output_metadata(ecx: &ExtCtxt, prefix: &str, name: &str, err_map: &ErrorMap)
-> Result<(), Box<Error>>
{
// Create the directory to place the file in.
let metadata_dir = get_metadata_dir(prefix);
create_dir_all(&metadata_dir)?;
// Open the metadata file.
let metadata_path = get_metadata_path(metadata_dir, name);
let mut metadata_file = File::create(&metadata_path)?;
// Construct a serializable map.
let json_map = err_map.iter().map(|(k, &ErrorInfo { description, use_site })| {
let key = k.as_str().to_string();
let value = ErrorMetadata {
description: description.map(|n| n.as_str().to_string()),
use_site: use_site.map(|sp| ErrorLocation::from_span(ecx, sp))
};
(key, value)
}).collect::<ErrorMetadataMap>();
// Write the data to the file, deleting it if the write fails.
let result = serde_json::to_writer(&mut metadata_file, &json_map);
if result.is_err() {
remove_file(&metadata_path)?;
}
Ok(result?)
} | /// JSON encodable error location type with filename and line number.
#[derive(PartialEq, Deserialize, Serialize)] | random_line_split |
cleanup.rs | extern crate diesel;
extern crate dotenv;
extern crate kuchiki;
extern crate rusoto_core;
extern crate rusoto_credential;
extern crate rusoto_s3;
extern crate server;
extern crate url;
use diesel::pg::PgConnection;
use diesel::prelude::*;
use dotenv::dotenv;
use kuchiki::traits::*;
use rusoto_core::Region;
use rusoto_s3::{DeleteObjectRequest, S3, S3Client};
use server::models::*;
use server::start_logging;
use std::env;
use url::Url;
fn cleanup(ad: &mut Ad) -> bool {
let document = kuchiki::parse_html().one(ad.html.clone());
let mut ret = false;
for like in document.select("h5._1qbu").unwrap() {
like.as_node().detach();
ret = true;
}
let mut images = ad.images.clone();
for img in document.select(".commentable_item img").unwrap() {
if let Some(src) = img.attributes.borrow_mut().get_mut("src") {
if let Some(pos) = images.iter().position(|x| x == src) {
images.remove(pos);
}
println!("deleting {}", src);
if let Ok(url) = src.parse::<Url>() {
let client = S3Client::simple(Region::UsEast1);
let res = client
.delete_object(&DeleteObjectRequest {
bucket: "pp-facebook-ads".to_string(),
key: url.path().trim_left_matches('/').to_string(),
..DeleteObjectRequest::default()
})
.sync();
*src = "".to_string();
if res.is_err() {
println!("Couldn't delete {} {:?}", src, res);
}
}
}
ret = true;
}
for comment in document.select(".commentable_item").unwrap() {
comment.as_node().detach();
ret = true;
}
ad.html = document
.select("div")
.unwrap()
.nth(0)
.unwrap()
.as_node()
.to_string();
ad.images = images;
ret
}
fn | () {
use server::schema::ads::dsl::*;
dotenv().ok();
start_logging();
let database_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set");
let conn = PgConnection::establish(&database_url).unwrap();
let dbads: Vec<Ad> = ads.order(created_at.desc()).load::<Ad>(&conn).unwrap();
for mut ad in dbads {
if cleanup(&mut ad) {
let document = kuchiki::parse_html().one(ad.html.clone());
println!("Cleaned {}", ad.id);
diesel::update(ads.find(ad.id.clone()))
.set((
html.eq(ad.html),
title.eq(get_title(&document).unwrap()),
message.eq(get_message(&document).unwrap()),
images.eq(ad.images),
))
.execute(&conn)
.unwrap();
} else {
println!("Skipped {}", ad.id);
}
}
}
| main | identifier_name |
cleanup.rs | extern crate diesel;
extern crate dotenv;
extern crate kuchiki;
extern crate rusoto_core;
extern crate rusoto_credential;
extern crate rusoto_s3;
extern crate server;
extern crate url;
use diesel::pg::PgConnection;
use diesel::prelude::*;
use dotenv::dotenv;
use kuchiki::traits::*;
use rusoto_core::Region;
use rusoto_s3::{DeleteObjectRequest, S3, S3Client};
use server::models::*;
use server::start_logging;
use std::env;
use url::Url;
fn cleanup(ad: &mut Ad) -> bool {
let document = kuchiki::parse_html().one(ad.html.clone());
let mut ret = false;
for like in document.select("h5._1qbu").unwrap() {
like.as_node().detach();
ret = true;
}
let mut images = ad.images.clone();
for img in document.select(".commentable_item img").unwrap() {
if let Some(src) = img.attributes.borrow_mut().get_mut("src") {
if let Some(pos) = images.iter().position(|x| x == src) {
images.remove(pos);
}
println!("deleting {}", src);
if let Ok(url) = src.parse::<Url>() {
let client = S3Client::simple(Region::UsEast1);
let res = client
.delete_object(&DeleteObjectRequest {
bucket: "pp-facebook-ads".to_string(),
key: url.path().trim_left_matches('/').to_string(),
..DeleteObjectRequest::default()
})
.sync();
*src = "".to_string();
if res.is_err() |
}
}
ret = true;
}
for comment in document.select(".commentable_item").unwrap() {
comment.as_node().detach();
ret = true;
}
ad.html = document
.select("div")
.unwrap()
.nth(0)
.unwrap()
.as_node()
.to_string();
ad.images = images;
ret
}
fn main() {
use server::schema::ads::dsl::*;
dotenv().ok();
start_logging();
let database_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set");
let conn = PgConnection::establish(&database_url).unwrap();
let dbads: Vec<Ad> = ads.order(created_at.desc()).load::<Ad>(&conn).unwrap();
for mut ad in dbads {
if cleanup(&mut ad) {
let document = kuchiki::parse_html().one(ad.html.clone());
println!("Cleaned {}", ad.id);
diesel::update(ads.find(ad.id.clone()))
.set((
html.eq(ad.html),
title.eq(get_title(&document).unwrap()),
message.eq(get_message(&document).unwrap()),
images.eq(ad.images),
))
.execute(&conn)
.unwrap();
} else {
println!("Skipped {}", ad.id);
}
}
}
| {
println!("Couldn't delete {} {:?}", src, res);
} | conditional_block |
cleanup.rs | extern crate diesel;
extern crate dotenv;
extern crate kuchiki;
extern crate rusoto_core;
extern crate rusoto_credential;
extern crate rusoto_s3;
extern crate server;
extern crate url;
use diesel::pg::PgConnection;
use diesel::prelude::*;
use dotenv::dotenv;
use kuchiki::traits::*;
use rusoto_core::Region;
use rusoto_s3::{DeleteObjectRequest, S3, S3Client};
use server::models::*;
use server::start_logging;
use std::env;
use url::Url;
fn cleanup(ad: &mut Ad) -> bool {
let document = kuchiki::parse_html().one(ad.html.clone());
let mut ret = false;
for like in document.select("h5._1qbu").unwrap() {
like.as_node().detach();
ret = true;
}
let mut images = ad.images.clone();
for img in document.select(".commentable_item img").unwrap() {
if let Some(src) = img.attributes.borrow_mut().get_mut("src") {
if let Some(pos) = images.iter().position(|x| x == src) {
images.remove(pos);
}
println!("deleting {}", src);
if let Ok(url) = src.parse::<Url>() {
let client = S3Client::simple(Region::UsEast1);
let res = client
.delete_object(&DeleteObjectRequest {
bucket: "pp-facebook-ads".to_string(),
key: url.path().trim_left_matches('/').to_string(),
..DeleteObjectRequest::default()
})
.sync();
*src = "".to_string();
if res.is_err() {
println!("Couldn't delete {} {:?}", src, res);
}
}
}
ret = true;
}
for comment in document.select(".commentable_item").unwrap() {
comment.as_node().detach();
ret = true;
}
ad.html = document
.select("div")
.unwrap()
.nth(0)
.unwrap()
.as_node()
.to_string();
ad.images = images;
ret
}
fn main() | .unwrap();
} else {
println!("Skipped {}", ad.id);
}
}
}
| {
use server::schema::ads::dsl::*;
dotenv().ok();
start_logging();
let database_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set");
let conn = PgConnection::establish(&database_url).unwrap();
let dbads: Vec<Ad> = ads.order(created_at.desc()).load::<Ad>(&conn).unwrap();
for mut ad in dbads {
if cleanup(&mut ad) {
let document = kuchiki::parse_html().one(ad.html.clone());
println!("Cleaned {}", ad.id);
diesel::update(ads.find(ad.id.clone()))
.set((
html.eq(ad.html),
title.eq(get_title(&document).unwrap()),
message.eq(get_message(&document).unwrap()),
images.eq(ad.images),
))
.execute(&conn) | identifier_body |
cleanup.rs | extern crate diesel;
extern crate dotenv;
extern crate kuchiki;
extern crate rusoto_core;
extern crate rusoto_credential;
extern crate rusoto_s3;
extern crate server;
extern crate url;
use diesel::pg::PgConnection;
use diesel::prelude::*;
use dotenv::dotenv;
use kuchiki::traits::*;
use rusoto_core::Region;
use rusoto_s3::{DeleteObjectRequest, S3, S3Client};
use server::models::*;
use server::start_logging;
use std::env;
use url::Url;
fn cleanup(ad: &mut Ad) -> bool {
let document = kuchiki::parse_html().one(ad.html.clone());
let mut ret = false;
for like in document.select("h5._1qbu").unwrap() {
like.as_node().detach();
ret = true;
}
let mut images = ad.images.clone();
for img in document.select(".commentable_item img").unwrap() {
if let Some(src) = img.attributes.borrow_mut().get_mut("src") {
if let Some(pos) = images.iter().position(|x| x == src) {
images.remove(pos);
}
println!("deleting {}", src);
if let Ok(url) = src.parse::<Url>() {
let client = S3Client::simple(Region::UsEast1);
let res = client
.delete_object(&DeleteObjectRequest {
bucket: "pp-facebook-ads".to_string(),
key: url.path().trim_left_matches('/').to_string(),
..DeleteObjectRequest::default()
})
.sync();
*src = "".to_string();
if res.is_err() {
println!("Couldn't delete {} {:?}", src, res);
}
}
}
ret = true;
}
for comment in document.select(".commentable_item").unwrap() {
comment.as_node().detach();
ret = true;
} | .unwrap()
.as_node()
.to_string();
ad.images = images;
ret
}
fn main() {
use server::schema::ads::dsl::*;
dotenv().ok();
start_logging();
let database_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set");
let conn = PgConnection::establish(&database_url).unwrap();
let dbads: Vec<Ad> = ads.order(created_at.desc()).load::<Ad>(&conn).unwrap();
for mut ad in dbads {
if cleanup(&mut ad) {
let document = kuchiki::parse_html().one(ad.html.clone());
println!("Cleaned {}", ad.id);
diesel::update(ads.find(ad.id.clone()))
.set((
html.eq(ad.html),
title.eq(get_title(&document).unwrap()),
message.eq(get_message(&document).unwrap()),
images.eq(ad.images),
))
.execute(&conn)
.unwrap();
} else {
println!("Skipped {}", ad.id);
}
}
} |
ad.html = document
.select("div")
.unwrap()
.nth(0) | random_line_split |
syst_rvr.rs | #[doc = "Register `SYST_RVR` reader"]
pub struct R(crate::R<SYST_RVR_SPEC>);
impl core::ops::Deref for R {
type Target = crate::R<SYST_RVR_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<crate::R<SYST_RVR_SPEC>> for R {
#[inline(always)]
fn from(reader: crate::R<SYST_RVR_SPEC>) -> Self {
R(reader)
}
}
#[doc = "Register `SYST_RVR` writer"]
pub struct W(crate::W<SYST_RVR_SPEC>);
impl core::ops::Deref for W {
type Target = crate::W<SYST_RVR_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl core::ops::DerefMut for W {
#[inline(always)]
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl From<crate::W<SYST_RVR_SPEC>> for W {
#[inline(always)]
fn from(writer: crate::W<SYST_RVR_SPEC>) -> Self {
W(writer)
}
}
#[doc = "Field `RELOAD` reader - Reload Value"]
pub struct RELOAD_R(crate::FieldReader<u32, u32>);
impl RELOAD_R {
pub(crate) fn new(bits: u32) -> Self {
RELOAD_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for RELOAD_R {
type Target = crate::FieldReader<u32, u32>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `RELOAD` writer - Reload Value"]
pub struct RELOAD_W<'a> {
w: &'a mut W,
}
impl<'a> RELOAD_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u32) -> &'a mut W {
self.w.bits = (self.w.bits &!0x00ff_ffff) | (value as u32 & 0x00ff_ffff);
self.w
}
}
impl R {
#[doc = "Bits 0:23 - Reload Value"]
#[inline(always)]
pub fn reload(&self) -> RELOAD_R {
RELOAD_R::new((self.bits & 0x00ff_ffff) as u32)
}
}
impl W {
#[doc = "Bits 0:23 - Reload Value"]
#[inline(always)]
pub fn reload(&mut self) -> RELOAD_W {
RELOAD_W { w: self }
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.0.bits(bits);
self
}
}
#[doc = "SysTick Reload Value Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [syst_rvr](index.html) module"]
pub struct SYST_RVR_SPEC;
impl crate::RegisterSpec for SYST_RVR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [syst_rvr::R](R) reader structure"]
impl crate::Readable for SYST_RVR_SPEC {
type Reader = R;
}
#[doc = "`write(|w|..)` method takes [syst_rvr::W](W) writer structure"]
impl crate::Writable for SYST_RVR_SPEC {
type Writer = W;
} | 0
}
} | #[doc = "`reset()` method sets SYST_RVR to value 0"]
impl crate::Resettable for SYST_RVR_SPEC {
#[inline(always)]
fn reset_value() -> Self::Ux { | random_line_split |
syst_rvr.rs | #[doc = "Register `SYST_RVR` reader"]
pub struct R(crate::R<SYST_RVR_SPEC>);
impl core::ops::Deref for R {
type Target = crate::R<SYST_RVR_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<crate::R<SYST_RVR_SPEC>> for R {
#[inline(always)]
fn from(reader: crate::R<SYST_RVR_SPEC>) -> Self {
R(reader)
}
}
#[doc = "Register `SYST_RVR` writer"]
pub struct W(crate::W<SYST_RVR_SPEC>);
impl core::ops::Deref for W {
type Target = crate::W<SYST_RVR_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl core::ops::DerefMut for W {
#[inline(always)]
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl From<crate::W<SYST_RVR_SPEC>> for W {
#[inline(always)]
fn from(writer: crate::W<SYST_RVR_SPEC>) -> Self {
W(writer)
}
}
#[doc = "Field `RELOAD` reader - Reload Value"]
pub struct RELOAD_R(crate::FieldReader<u32, u32>);
impl RELOAD_R {
pub(crate) fn new(bits: u32) -> Self {
RELOAD_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for RELOAD_R {
type Target = crate::FieldReader<u32, u32>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `RELOAD` writer - Reload Value"]
pub struct RELOAD_W<'a> {
w: &'a mut W,
}
impl<'a> RELOAD_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u32) -> &'a mut W {
self.w.bits = (self.w.bits &!0x00ff_ffff) | (value as u32 & 0x00ff_ffff);
self.w
}
}
impl R {
#[doc = "Bits 0:23 - Reload Value"]
#[inline(always)]
pub fn reload(&self) -> RELOAD_R {
RELOAD_R::new((self.bits & 0x00ff_ffff) as u32)
}
}
impl W {
#[doc = "Bits 0:23 - Reload Value"]
#[inline(always)]
pub fn reload(&mut self) -> RELOAD_W {
RELOAD_W { w: self }
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self |
}
#[doc = "SysTick Reload Value Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [syst_rvr](index.html) module"]
pub struct SYST_RVR_SPEC;
impl crate::RegisterSpec for SYST_RVR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [syst_rvr::R](R) reader structure"]
impl crate::Readable for SYST_RVR_SPEC {
type Reader = R;
}
#[doc = "`write(|w|..)` method takes [syst_rvr::W](W) writer structure"]
impl crate::Writable for SYST_RVR_SPEC {
type Writer = W;
}
#[doc = "`reset()` method sets SYST_RVR to value 0"]
impl crate::Resettable for SYST_RVR_SPEC {
#[inline(always)]
fn reset_value() -> Self::Ux {
0
}
}
| {
self.0.bits(bits);
self
} | identifier_body |
syst_rvr.rs | #[doc = "Register `SYST_RVR` reader"]
pub struct R(crate::R<SYST_RVR_SPEC>);
impl core::ops::Deref for R {
type Target = crate::R<SYST_RVR_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<crate::R<SYST_RVR_SPEC>> for R {
#[inline(always)]
fn from(reader: crate::R<SYST_RVR_SPEC>) -> Self {
R(reader)
}
}
#[doc = "Register `SYST_RVR` writer"]
pub struct W(crate::W<SYST_RVR_SPEC>);
impl core::ops::Deref for W {
type Target = crate::W<SYST_RVR_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl core::ops::DerefMut for W {
#[inline(always)]
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl From<crate::W<SYST_RVR_SPEC>> for W {
#[inline(always)]
fn from(writer: crate::W<SYST_RVR_SPEC>) -> Self {
W(writer)
}
}
#[doc = "Field `RELOAD` reader - Reload Value"]
pub struct RELOAD_R(crate::FieldReader<u32, u32>);
impl RELOAD_R {
pub(crate) fn new(bits: u32) -> Self {
RELOAD_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for RELOAD_R {
type Target = crate::FieldReader<u32, u32>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `RELOAD` writer - Reload Value"]
pub struct RELOAD_W<'a> {
w: &'a mut W,
}
impl<'a> RELOAD_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn | (self, value: u32) -> &'a mut W {
self.w.bits = (self.w.bits &!0x00ff_ffff) | (value as u32 & 0x00ff_ffff);
self.w
}
}
impl R {
#[doc = "Bits 0:23 - Reload Value"]
#[inline(always)]
pub fn reload(&self) -> RELOAD_R {
RELOAD_R::new((self.bits & 0x00ff_ffff) as u32)
}
}
impl W {
#[doc = "Bits 0:23 - Reload Value"]
#[inline(always)]
pub fn reload(&mut self) -> RELOAD_W {
RELOAD_W { w: self }
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.0.bits(bits);
self
}
}
#[doc = "SysTick Reload Value Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [syst_rvr](index.html) module"]
pub struct SYST_RVR_SPEC;
impl crate::RegisterSpec for SYST_RVR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [syst_rvr::R](R) reader structure"]
impl crate::Readable for SYST_RVR_SPEC {
type Reader = R;
}
#[doc = "`write(|w|..)` method takes [syst_rvr::W](W) writer structure"]
impl crate::Writable for SYST_RVR_SPEC {
type Writer = W;
}
#[doc = "`reset()` method sets SYST_RVR to value 0"]
impl crate::Resettable for SYST_RVR_SPEC {
#[inline(always)]
fn reset_value() -> Self::Ux {
0
}
}
| bits | identifier_name |
generic-function.rs | // Copyright 2013-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.
// min-lldb-version: 310
// compile-flags:-g
// === GDB TESTS ===================================================================================
// gdb-command:run
// gdb-command:print *t0
// gdb-check:$1 = 1
// gdb-command:print *t1
// gdb-check:$2 = 2.5
// gdb-command:print ret
// gdb-check:$3 = {{1, 2.5}, {2.5, 1}}
// gdb-command:continue
// gdb-command:print *t0
// gdb-check:$4 = 3.5
// gdb-command:print *t1
// gdb-check:$5 = 4
// gdb-command:print ret
// gdb-check:$6 = {{3.5, 4}, {4, 3.5}}
// gdb-command:continue
// gdb-command:print *t0
// gdb-check:$7 = 5
// gdb-command:print *t1
// gdb-check:$8 = {a = 6, b = 7.5}
// gdb-command:print ret
// gdb-check:$9 = {{5, {a = 6, b = 7.5}}, {{a = 6, b = 7.5}, 5}}
// gdb-command:continue
// === LLDB TESTS ==================================================================================
// lldb-command:run
// lldb-command:print *t0
// lldb-check:[...]$0 = 1
// lldb-command:print *t1
// lldb-check:[...]$1 = 2.5
// lldb-command:print ret
// lldb-check:[...]$2 = ((1, 2.5), (2.5, 1))
// lldb-command:continue
// lldb-command:print *t0
// lldb-check:[...]$3 = 3.5
// lldb-command:print *t1
// lldb-check:[...]$4 = 4
// lldb-command:print ret
// lldb-check:[...]$5 = ((3.5, 4), (4, 3.5))
// lldb-command:continue
// lldb-command:print *t0
// lldb-check:[...]$6 = 5
// lldb-command:print *t1
// lldb-check:[...]$7 = Struct { a: 6, b: 7.5 }
// lldb-command:print ret
// lldb-check:[...]$8 = ((5, Struct { a: 6, b: 7.5 }), (Struct { a: 6, b: 7.5 }, 5))
// lldb-command:continue
#![omit_gdb_pretty_printer_section]
#[derive(Clone)]
struct Struct {
a: int,
b: f64
}
fn dup_tup<T0: Clone, T1: Clone>(t0: &T0, t1: &T1) -> ((T0, T1), (T1, T0)) {
let ret = ((t0.clone(), t1.clone()), (t1.clone(), t0.clone()));
zzz(); // #break
ret
}
fn main() {
let _ = dup_tup(&1, &2.5f64);
let _ = dup_tup(&3.5f64, &4_u16);
let _ = dup_tup(&5, &Struct { a: 6, b: 7.5 });
}
fn | () {()}
| zzz | identifier_name |
generic-function.rs | // Copyright 2013-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.
// min-lldb-version: 310
// compile-flags:-g
// === GDB TESTS ===================================================================================
// gdb-command:run
// gdb-command:print *t0
// gdb-check:$1 = 1
// gdb-command:print *t1
// gdb-check:$2 = 2.5
// gdb-command:print ret
// gdb-check:$3 = {{1, 2.5}, {2.5, 1}}
// gdb-command:continue
// gdb-command:print *t0
// gdb-check:$4 = 3.5
// gdb-command:print *t1
// gdb-check:$5 = 4
// gdb-command:print ret
// gdb-check:$6 = {{3.5, 4}, {4, 3.5}}
// gdb-command:continue
// gdb-command:print *t0
// gdb-check:$7 = 5
// gdb-command:print *t1
// gdb-check:$8 = {a = 6, b = 7.5}
// gdb-command:print ret
// gdb-check:$9 = {{5, {a = 6, b = 7.5}}, {{a = 6, b = 7.5}, 5}}
// gdb-command:continue
// === LLDB TESTS ==================================================================================
// lldb-command:run
// lldb-command:print *t0
// lldb-check:[...]$0 = 1
// lldb-command:print *t1
// lldb-check:[...]$1 = 2.5
// lldb-command:print ret
// lldb-check:[...]$2 = ((1, 2.5), (2.5, 1))
// lldb-command:continue
// lldb-command:print *t0
// lldb-check:[...]$3 = 3.5
// lldb-command:print *t1
// lldb-check:[...]$4 = 4 |
// lldb-command:print *t0
// lldb-check:[...]$6 = 5
// lldb-command:print *t1
// lldb-check:[...]$7 = Struct { a: 6, b: 7.5 }
// lldb-command:print ret
// lldb-check:[...]$8 = ((5, Struct { a: 6, b: 7.5 }), (Struct { a: 6, b: 7.5 }, 5))
// lldb-command:continue
#![omit_gdb_pretty_printer_section]
#[derive(Clone)]
struct Struct {
a: int,
b: f64
}
fn dup_tup<T0: Clone, T1: Clone>(t0: &T0, t1: &T1) -> ((T0, T1), (T1, T0)) {
let ret = ((t0.clone(), t1.clone()), (t1.clone(), t0.clone()));
zzz(); // #break
ret
}
fn main() {
let _ = dup_tup(&1, &2.5f64);
let _ = dup_tup(&3.5f64, &4_u16);
let _ = dup_tup(&5, &Struct { a: 6, b: 7.5 });
}
fn zzz() {()} | // lldb-command:print ret
// lldb-check:[...]$5 = ((3.5, 4), (4, 3.5))
// lldb-command:continue | random_line_split |
mod.rs | //////////////////////////////////////////////////////////////////////////////
// File: rust-worldgen/noise/perlin/mod.rs
//////////////////////////////////////////////////////////////////////////////
// Copyright 2015 Samuel Sleight
//
// 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.
//////////////////////////////////////////////////////////////////////////////
//! A provider of perlin noise.
//!
//! Perlin noise is generated by combining a number of different values
//! of coherent noise (known as octaves).
//!
//! The perlin noise source has a number of different properties that can
//! be customised: the number of octaves, and the frequency, persistence,
//! and lacunarity of the noise.
use std::default::Default;
use super::NoiseProvider;
use super::coherent::CoherentNoise;
pub use self::property::{Octaves, Frequency, Persistence, Lacunarity};
use self::property::Property;
mod property;
/// The perlin noise source
///
/// # Example
/// | /// # use worldgen::noise::perlin::{PerlinNoise, Octaves};
/// # use worldgen::noise::NoiseProvider;
/// let noise = PerlinNoise::new()
/// .set(Octaves::of(5));
///
/// let value = noise.generate(1.5, 2.5, 15);
/// ```
#[derive(Default, Debug, Copy, Clone)]
pub struct PerlinNoise {
octaves: Octaves,
freq: Frequency,
pers: Persistence,
lacu: Lacunarity
}
impl PerlinNoise {
/// Construct the default perlin source.
///
/// The default values are:
///
/// ```text
/// octaves = 8
/// frequency = 1.0
/// persistence = 0.5
/// lacunarity = 2.0
/// ```
pub fn new() -> PerlinNoise {
Default::default()
}
/// Set a property on the noise source.
pub fn set<T: Property>(self, property: T) -> PerlinNoise {
property.set_to(self)
}
fn set_octaves(self, octaves: Octaves) -> PerlinNoise {
PerlinNoise {
octaves,
..self
}
}
fn set_frequency(self, freq: Frequency) -> PerlinNoise {
PerlinNoise {
freq,
..self
}
}
fn set_persistence(self, pers: Persistence) -> PerlinNoise {
PerlinNoise {
pers,
..self
}
}
fn set_lacunarity(self, lacu: Lacunarity) -> PerlinNoise {
PerlinNoise {
lacu,
..self
}
}
}
impl NoiseProvider for PerlinNoise {
fn generate(&self, x: f64, y: f64, seed: u64) -> f64 {
let mut x = x * self.freq.value;
let mut y = y * self.freq.value;
let mut pers = 1.0f64;
(0.. self.octaves.value).fold(0.0, |value, octave| {
let seed = seed + octave as u64;
let value = value + CoherentNoise.generate(x, y, seed) * pers;
x *= self.lacu.value;
y *= self.lacu.value;
pers *= self.pers.value;
value
})
}
} | /// ``` | random_line_split |
mod.rs | //////////////////////////////////////////////////////////////////////////////
// File: rust-worldgen/noise/perlin/mod.rs
//////////////////////////////////////////////////////////////////////////////
// Copyright 2015 Samuel Sleight
//
// 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.
//////////////////////////////////////////////////////////////////////////////
//! A provider of perlin noise.
//!
//! Perlin noise is generated by combining a number of different values
//! of coherent noise (known as octaves).
//!
//! The perlin noise source has a number of different properties that can
//! be customised: the number of octaves, and the frequency, persistence,
//! and lacunarity of the noise.
use std::default::Default;
use super::NoiseProvider;
use super::coherent::CoherentNoise;
pub use self::property::{Octaves, Frequency, Persistence, Lacunarity};
use self::property::Property;
mod property;
/// The perlin noise source
///
/// # Example
///
/// ```
/// # use worldgen::noise::perlin::{PerlinNoise, Octaves};
/// # use worldgen::noise::NoiseProvider;
/// let noise = PerlinNoise::new()
/// .set(Octaves::of(5));
///
/// let value = noise.generate(1.5, 2.5, 15);
/// ```
#[derive(Default, Debug, Copy, Clone)]
pub struct PerlinNoise {
octaves: Octaves,
freq: Frequency,
pers: Persistence,
lacu: Lacunarity
}
impl PerlinNoise {
/// Construct the default perlin source.
///
/// The default values are:
///
/// ```text
/// octaves = 8
/// frequency = 1.0
/// persistence = 0.5
/// lacunarity = 2.0
/// ```
pub fn new() -> PerlinNoise {
Default::default()
}
/// Set a property on the noise source.
pub fn set<T: Property>(self, property: T) -> PerlinNoise {
property.set_to(self)
}
fn | (self, octaves: Octaves) -> PerlinNoise {
PerlinNoise {
octaves,
..self
}
}
fn set_frequency(self, freq: Frequency) -> PerlinNoise {
PerlinNoise {
freq,
..self
}
}
fn set_persistence(self, pers: Persistence) -> PerlinNoise {
PerlinNoise {
pers,
..self
}
}
fn set_lacunarity(self, lacu: Lacunarity) -> PerlinNoise {
PerlinNoise {
lacu,
..self
}
}
}
impl NoiseProvider for PerlinNoise {
fn generate(&self, x: f64, y: f64, seed: u64) -> f64 {
let mut x = x * self.freq.value;
let mut y = y * self.freq.value;
let mut pers = 1.0f64;
(0.. self.octaves.value).fold(0.0, |value, octave| {
let seed = seed + octave as u64;
let value = value + CoherentNoise.generate(x, y, seed) * pers;
x *= self.lacu.value;
y *= self.lacu.value;
pers *= self.pers.value;
value
})
}
}
| set_octaves | identifier_name |
mod.rs | //////////////////////////////////////////////////////////////////////////////
// File: rust-worldgen/noise/perlin/mod.rs
//////////////////////////////////////////////////////////////////////////////
// Copyright 2015 Samuel Sleight
//
// 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.
//////////////////////////////////////////////////////////////////////////////
//! A provider of perlin noise.
//!
//! Perlin noise is generated by combining a number of different values
//! of coherent noise (known as octaves).
//!
//! The perlin noise source has a number of different properties that can
//! be customised: the number of octaves, and the frequency, persistence,
//! and lacunarity of the noise.
use std::default::Default;
use super::NoiseProvider;
use super::coherent::CoherentNoise;
pub use self::property::{Octaves, Frequency, Persistence, Lacunarity};
use self::property::Property;
mod property;
/// The perlin noise source
///
/// # Example
///
/// ```
/// # use worldgen::noise::perlin::{PerlinNoise, Octaves};
/// # use worldgen::noise::NoiseProvider;
/// let noise = PerlinNoise::new()
/// .set(Octaves::of(5));
///
/// let value = noise.generate(1.5, 2.5, 15);
/// ```
#[derive(Default, Debug, Copy, Clone)]
pub struct PerlinNoise {
octaves: Octaves,
freq: Frequency,
pers: Persistence,
lacu: Lacunarity
}
impl PerlinNoise {
/// Construct the default perlin source.
///
/// The default values are:
///
/// ```text
/// octaves = 8
/// frequency = 1.0
/// persistence = 0.5
/// lacunarity = 2.0
/// ```
pub fn new() -> PerlinNoise {
Default::default()
}
/// Set a property on the noise source.
pub fn set<T: Property>(self, property: T) -> PerlinNoise {
property.set_to(self)
}
fn set_octaves(self, octaves: Octaves) -> PerlinNoise {
PerlinNoise {
octaves,
..self
}
}
fn set_frequency(self, freq: Frequency) -> PerlinNoise {
PerlinNoise {
freq,
..self
}
}
fn set_persistence(self, pers: Persistence) -> PerlinNoise {
PerlinNoise {
pers,
..self
}
}
fn set_lacunarity(self, lacu: Lacunarity) -> PerlinNoise |
}
impl NoiseProvider for PerlinNoise {
fn generate(&self, x: f64, y: f64, seed: u64) -> f64 {
let mut x = x * self.freq.value;
let mut y = y * self.freq.value;
let mut pers = 1.0f64;
(0.. self.octaves.value).fold(0.0, |value, octave| {
let seed = seed + octave as u64;
let value = value + CoherentNoise.generate(x, y, seed) * pers;
x *= self.lacu.value;
y *= self.lacu.value;
pers *= self.pers.value;
value
})
}
}
| {
PerlinNoise {
lacu,
..self
}
} | identifier_body |
list.rs | //! This module has containers for storing the tasks spawned on a scheduler. The
//! `OwnedTasks` container is thread-safe but can only store tasks that
//! implement Send. The `LocalOwnedTasks` container is not thread safe, but can
//! store non-Send tasks.
//!
//! The collections can be closed to prevent adding new tasks during shutdown of
//! the scheduler with the collection.
use crate::future::Future;
use crate::loom::cell::UnsafeCell;
use crate::loom::sync::Mutex;
use crate::runtime::task::{JoinHandle, LocalNotified, Notified, Schedule, Task};
use crate::util::linked_list::{Link, LinkedList};
use std::marker::PhantomData;
// The id from the module below is used to verify whether a given task is stored
// in this OwnedTasks, or some other task. The counter starts at one so we can
// use zero for tasks not owned by any list.
//
// The safety checks in this file can technically be violated if the counter is
// overflown, but the checks are not supposed to ever fail unless there is a
// bug in Tokio, so we accept that certain bugs would not be caught if the two
// mixed up runtimes happen to have the same id.
cfg_has_atomic_u64! {
use std::sync::atomic::{AtomicU64, Ordering};
static NEXT_OWNED_TASKS_ID: AtomicU64 = AtomicU64::new(1);
fn get_next_id() -> u64 {
loop {
let id = NEXT_OWNED_TASKS_ID.fetch_add(1, Ordering::Relaxed);
if id!= 0 {
return id;
}
}
}
}
cfg_not_has_atomic_u64! {
use std::sync::atomic::{AtomicU32, Ordering};
static NEXT_OWNED_TASKS_ID: AtomicU32 = AtomicU32::new(1);
fn get_next_id() -> u64 {
loop {
let id = NEXT_OWNED_TASKS_ID.fetch_add(1, Ordering::Relaxed);
if id!= 0 {
return u64::from(id);
}
}
}
}
pub(crate) struct OwnedTasks<S:'static> {
inner: Mutex<OwnedTasksInner<S>>,
id: u64,
}
pub(crate) struct LocalOwnedTasks<S:'static> {
inner: UnsafeCell<OwnedTasksInner<S>>,
id: u64,
_not_send_or_sync: PhantomData<*const ()>,
}
struct OwnedTasksInner<S:'static> {
list: LinkedList<Task<S>, <Task<S> as Link>::Target>,
closed: bool,
}
impl<S:'static> OwnedTasks<S> {
pub(crate) fn new() -> Self {
Self {
inner: Mutex::new(OwnedTasksInner {
list: LinkedList::new(),
closed: false,
}),
id: get_next_id(),
}
}
/// Binds the provided task to this OwnedTasks instance. This fails if the
/// OwnedTasks has been closed.
pub(crate) fn bind<T>(
&self,
task: T,
scheduler: S,
) -> (JoinHandle<T::Output>, Option<Notified<S>>)
where
S: Schedule,
T: Future + Send +'static,
T::Output: Send +'static,
{
let (task, notified, join) = super::new_task(task, scheduler);
unsafe {
// safety: We just created the task, so we have exclusive access
// to the field.
task.header().set_owner_id(self.id);
}
let mut lock = self.inner.lock();
if lock.closed {
drop(lock);
drop(notified);
task.shutdown();
(join, None)
} else {
lock.list.push_front(task);
(join, Some(notified))
}
}
/// Asserts that the given task is owned by this OwnedTasks and convert it to
/// a LocalNotified, giving the thread permission to poll this task.
#[inline]
pub(crate) fn | (&self, task: Notified<S>) -> LocalNotified<S> {
assert_eq!(task.header().get_owner_id(), self.id);
// safety: All tasks bound to this OwnedTasks are Send, so it is safe
// to poll it on this thread no matter what thread we are on.
LocalNotified {
task: task.0,
_not_send: PhantomData,
}
}
/// Shuts down all tasks in the collection. This call also closes the
/// collection, preventing new items from being added.
pub(crate) fn close_and_shutdown_all(&self)
where
S: Schedule,
{
// The first iteration of the loop was unrolled so it can set the
// closed bool.
let first_task = {
let mut lock = self.inner.lock();
lock.closed = true;
lock.list.pop_back()
};
match first_task {
Some(task) => task.shutdown(),
None => return,
}
loop {
let task = match self.inner.lock().list.pop_back() {
Some(task) => task,
None => return,
};
task.shutdown();
}
}
pub(crate) fn remove(&self, task: &Task<S>) -> Option<Task<S>> {
let task_id = task.header().get_owner_id();
if task_id == 0 {
// The task is unowned.
return None;
}
assert_eq!(task_id, self.id);
// safety: We just checked that the provided task is not in some other
// linked list.
unsafe { self.inner.lock().list.remove(task.header().into()) }
}
pub(crate) fn is_empty(&self) -> bool {
self.inner.lock().list.is_empty()
}
}
impl<S:'static> LocalOwnedTasks<S> {
pub(crate) fn new() -> Self {
Self {
inner: UnsafeCell::new(OwnedTasksInner {
list: LinkedList::new(),
closed: false,
}),
id: get_next_id(),
_not_send_or_sync: PhantomData,
}
}
pub(crate) fn bind<T>(
&self,
task: T,
scheduler: S,
) -> (JoinHandle<T::Output>, Option<Notified<S>>)
where
S: Schedule,
T: Future +'static,
T::Output:'static,
{
let (task, notified, join) = super::new_task(task, scheduler);
unsafe {
// safety: We just created the task, so we have exclusive access
// to the field.
task.header().set_owner_id(self.id);
}
if self.is_closed() {
drop(notified);
task.shutdown();
(join, None)
} else {
self.with_inner(|inner| {
inner.list.push_front(task);
});
(join, Some(notified))
}
}
/// Shuts down all tasks in the collection. This call also closes the
/// collection, preventing new items from being added.
pub(crate) fn close_and_shutdown_all(&self)
where
S: Schedule,
{
self.with_inner(|inner| inner.closed = true);
while let Some(task) = self.with_inner(|inner| inner.list.pop_back()) {
task.shutdown();
}
}
pub(crate) fn remove(&self, task: &Task<S>) -> Option<Task<S>> {
let task_id = task.header().get_owner_id();
if task_id == 0 {
// The task is unowned.
return None;
}
assert_eq!(task_id, self.id);
self.with_inner(|inner|
// safety: We just checked that the provided task is not in some
// other linked list.
unsafe { inner.list.remove(task.header().into()) })
}
/// Asserts that the given task is owned by this LocalOwnedTasks and convert
/// it to a LocalNotified, giving the thread permission to poll this task.
#[inline]
pub(crate) fn assert_owner(&self, task: Notified<S>) -> LocalNotified<S> {
assert_eq!(task.header().get_owner_id(), self.id);
// safety: The task was bound to this LocalOwnedTasks, and the
// LocalOwnedTasks is not Send or Sync, so we are on the right thread
// for polling this task.
LocalNotified {
task: task.0,
_not_send: PhantomData,
}
}
#[inline]
fn with_inner<F, T>(&self, f: F) -> T
where
F: FnOnce(&mut OwnedTasksInner<S>) -> T,
{
// safety: This type is not Sync, so concurrent calls of this method
// can't happen. Furthermore, all uses of this method in this file make
// sure that they don't call `with_inner` recursively.
self.inner.with_mut(|ptr| unsafe { f(&mut *ptr) })
}
pub(crate) fn is_closed(&self) -> bool {
self.with_inner(|inner| inner.closed)
}
pub(crate) fn is_empty(&self) -> bool {
self.with_inner(|inner| inner.list.is_empty())
}
}
#[cfg(all(test))]
mod tests {
use super::*;
// This test may run in parallel with other tests, so we only test that ids
// come in increasing order.
#[test]
fn test_id_not_broken() {
let mut last_id = get_next_id();
assert_ne!(last_id, 0);
for _ in 0..1000 {
let next_id = get_next_id();
assert_ne!(next_id, 0);
assert!(last_id < next_id);
last_id = next_id;
}
}
}
| assert_owner | identifier_name |
list.rs | //! This module has containers for storing the tasks spawned on a scheduler. The
//! `OwnedTasks` container is thread-safe but can only store tasks that
//! implement Send. The `LocalOwnedTasks` container is not thread safe, but can
//! store non-Send tasks.
//!
//! The collections can be closed to prevent adding new tasks during shutdown of
//! the scheduler with the collection.
use crate::future::Future;
use crate::loom::cell::UnsafeCell;
use crate::loom::sync::Mutex;
use crate::runtime::task::{JoinHandle, LocalNotified, Notified, Schedule, Task};
use crate::util::linked_list::{Link, LinkedList};
use std::marker::PhantomData;
// The id from the module below is used to verify whether a given task is stored
// in this OwnedTasks, or some other task. The counter starts at one so we can
// use zero for tasks not owned by any list.
//
// The safety checks in this file can technically be violated if the counter is
// overflown, but the checks are not supposed to ever fail unless there is a
// bug in Tokio, so we accept that certain bugs would not be caught if the two
// mixed up runtimes happen to have the same id.
cfg_has_atomic_u64! {
use std::sync::atomic::{AtomicU64, Ordering};
static NEXT_OWNED_TASKS_ID: AtomicU64 = AtomicU64::new(1);
fn get_next_id() -> u64 {
loop {
let id = NEXT_OWNED_TASKS_ID.fetch_add(1, Ordering::Relaxed);
if id!= 0 {
return id;
}
}
}
}
cfg_not_has_atomic_u64! {
use std::sync::atomic::{AtomicU32, Ordering};
static NEXT_OWNED_TASKS_ID: AtomicU32 = AtomicU32::new(1);
fn get_next_id() -> u64 {
loop {
let id = NEXT_OWNED_TASKS_ID.fetch_add(1, Ordering::Relaxed);
if id!= 0 {
return u64::from(id);
}
}
}
}
pub(crate) struct OwnedTasks<S:'static> {
inner: Mutex<OwnedTasksInner<S>>,
id: u64,
}
pub(crate) struct LocalOwnedTasks<S:'static> {
inner: UnsafeCell<OwnedTasksInner<S>>,
id: u64,
_not_send_or_sync: PhantomData<*const ()>,
}
struct OwnedTasksInner<S:'static> {
list: LinkedList<Task<S>, <Task<S> as Link>::Target>,
closed: bool,
}
impl<S:'static> OwnedTasks<S> {
pub(crate) fn new() -> Self {
Self {
inner: Mutex::new(OwnedTasksInner {
list: LinkedList::new(),
closed: false,
}),
id: get_next_id(),
}
}
/// Binds the provided task to this OwnedTasks instance. This fails if the
/// OwnedTasks has been closed.
pub(crate) fn bind<T>(
&self,
task: T,
scheduler: S,
) -> (JoinHandle<T::Output>, Option<Notified<S>>)
where
S: Schedule,
T: Future + Send +'static,
T::Output: Send +'static,
{
let (task, notified, join) = super::new_task(task, scheduler);
unsafe {
// safety: We just created the task, so we have exclusive access
// to the field.
task.header().set_owner_id(self.id);
}
let mut lock = self.inner.lock();
if lock.closed {
drop(lock);
drop(notified);
task.shutdown();
(join, None)
} else {
lock.list.push_front(task);
(join, Some(notified))
}
}
/// Asserts that the given task is owned by this OwnedTasks and convert it to
/// a LocalNotified, giving the thread permission to poll this task.
#[inline]
pub(crate) fn assert_owner(&self, task: Notified<S>) -> LocalNotified<S> {
assert_eq!(task.header().get_owner_id(), self.id);
// safety: All tasks bound to this OwnedTasks are Send, so it is safe
// to poll it on this thread no matter what thread we are on.
LocalNotified {
task: task.0,
_not_send: PhantomData,
}
}
/// Shuts down all tasks in the collection. This call also closes the
/// collection, preventing new items from being added.
pub(crate) fn close_and_shutdown_all(&self)
where
S: Schedule,
| }
}
pub(crate) fn remove(&self, task: &Task<S>) -> Option<Task<S>> {
let task_id = task.header().get_owner_id();
if task_id == 0 {
// The task is unowned.
return None;
}
assert_eq!(task_id, self.id);
// safety: We just checked that the provided task is not in some other
// linked list.
unsafe { self.inner.lock().list.remove(task.header().into()) }
}
pub(crate) fn is_empty(&self) -> bool {
self.inner.lock().list.is_empty()
}
}
impl<S:'static> LocalOwnedTasks<S> {
pub(crate) fn new() -> Self {
Self {
inner: UnsafeCell::new(OwnedTasksInner {
list: LinkedList::new(),
closed: false,
}),
id: get_next_id(),
_not_send_or_sync: PhantomData,
}
}
pub(crate) fn bind<T>(
&self,
task: T,
scheduler: S,
) -> (JoinHandle<T::Output>, Option<Notified<S>>)
where
S: Schedule,
T: Future +'static,
T::Output:'static,
{
let (task, notified, join) = super::new_task(task, scheduler);
unsafe {
// safety: We just created the task, so we have exclusive access
// to the field.
task.header().set_owner_id(self.id);
}
if self.is_closed() {
drop(notified);
task.shutdown();
(join, None)
} else {
self.with_inner(|inner| {
inner.list.push_front(task);
});
(join, Some(notified))
}
}
/// Shuts down all tasks in the collection. This call also closes the
/// collection, preventing new items from being added.
pub(crate) fn close_and_shutdown_all(&self)
where
S: Schedule,
{
self.with_inner(|inner| inner.closed = true);
while let Some(task) = self.with_inner(|inner| inner.list.pop_back()) {
task.shutdown();
}
}
pub(crate) fn remove(&self, task: &Task<S>) -> Option<Task<S>> {
let task_id = task.header().get_owner_id();
if task_id == 0 {
// The task is unowned.
return None;
}
assert_eq!(task_id, self.id);
self.with_inner(|inner|
// safety: We just checked that the provided task is not in some
// other linked list.
unsafe { inner.list.remove(task.header().into()) })
}
/// Asserts that the given task is owned by this LocalOwnedTasks and convert
/// it to a LocalNotified, giving the thread permission to poll this task.
#[inline]
pub(crate) fn assert_owner(&self, task: Notified<S>) -> LocalNotified<S> {
assert_eq!(task.header().get_owner_id(), self.id);
// safety: The task was bound to this LocalOwnedTasks, and the
// LocalOwnedTasks is not Send or Sync, so we are on the right thread
// for polling this task.
LocalNotified {
task: task.0,
_not_send: PhantomData,
}
}
#[inline]
fn with_inner<F, T>(&self, f: F) -> T
where
F: FnOnce(&mut OwnedTasksInner<S>) -> T,
{
// safety: This type is not Sync, so concurrent calls of this method
// can't happen. Furthermore, all uses of this method in this file make
// sure that they don't call `with_inner` recursively.
self.inner.with_mut(|ptr| unsafe { f(&mut *ptr) })
}
pub(crate) fn is_closed(&self) -> bool {
self.with_inner(|inner| inner.closed)
}
pub(crate) fn is_empty(&self) -> bool {
self.with_inner(|inner| inner.list.is_empty())
}
}
#[cfg(all(test))]
mod tests {
use super::*;
// This test may run in parallel with other tests, so we only test that ids
// come in increasing order.
#[test]
fn test_id_not_broken() {
let mut last_id = get_next_id();
assert_ne!(last_id, 0);
for _ in 0..1000 {
let next_id = get_next_id();
assert_ne!(next_id, 0);
assert!(last_id < next_id);
last_id = next_id;
}
}
}
| {
// The first iteration of the loop was unrolled so it can set the
// closed bool.
let first_task = {
let mut lock = self.inner.lock();
lock.closed = true;
lock.list.pop_back()
};
match first_task {
Some(task) => task.shutdown(),
None => return,
}
loop {
let task = match self.inner.lock().list.pop_back() {
Some(task) => task,
None => return,
};
task.shutdown(); | identifier_body |
list.rs | //! This module has containers for storing the tasks spawned on a scheduler. The
//! `OwnedTasks` container is thread-safe but can only store tasks that
//! implement Send. The `LocalOwnedTasks` container is not thread safe, but can
//! store non-Send tasks.
//!
//! The collections can be closed to prevent adding new tasks during shutdown of
//! the scheduler with the collection.
use crate::future::Future;
use crate::loom::cell::UnsafeCell;
use crate::loom::sync::Mutex;
use crate::runtime::task::{JoinHandle, LocalNotified, Notified, Schedule, Task};
use crate::util::linked_list::{Link, LinkedList};
use std::marker::PhantomData;
// The id from the module below is used to verify whether a given task is stored
// in this OwnedTasks, or some other task. The counter starts at one so we can
// use zero for tasks not owned by any list.
//
// The safety checks in this file can technically be violated if the counter is
// overflown, but the checks are not supposed to ever fail unless there is a
// bug in Tokio, so we accept that certain bugs would not be caught if the two
// mixed up runtimes happen to have the same id.
cfg_has_atomic_u64! {
use std::sync::atomic::{AtomicU64, Ordering};
static NEXT_OWNED_TASKS_ID: AtomicU64 = AtomicU64::new(1);
fn get_next_id() -> u64 {
loop {
let id = NEXT_OWNED_TASKS_ID.fetch_add(1, Ordering::Relaxed);
if id!= 0 {
return id;
}
}
}
}
cfg_not_has_atomic_u64! {
use std::sync::atomic::{AtomicU32, Ordering};
static NEXT_OWNED_TASKS_ID: AtomicU32 = AtomicU32::new(1);
fn get_next_id() -> u64 {
loop {
let id = NEXT_OWNED_TASKS_ID.fetch_add(1, Ordering::Relaxed);
if id!= 0 {
return u64::from(id);
}
}
}
}
pub(crate) struct OwnedTasks<S:'static> {
inner: Mutex<OwnedTasksInner<S>>,
id: u64,
}
pub(crate) struct LocalOwnedTasks<S:'static> {
inner: UnsafeCell<OwnedTasksInner<S>>,
id: u64,
_not_send_or_sync: PhantomData<*const ()>,
}
struct OwnedTasksInner<S:'static> {
list: LinkedList<Task<S>, <Task<S> as Link>::Target>,
closed: bool,
}
impl<S:'static> OwnedTasks<S> {
pub(crate) fn new() -> Self {
Self {
inner: Mutex::new(OwnedTasksInner {
list: LinkedList::new(),
closed: false,
}),
id: get_next_id(),
}
}
/// Binds the provided task to this OwnedTasks instance. This fails if the
/// OwnedTasks has been closed.
pub(crate) fn bind<T>(
&self,
task: T,
scheduler: S,
) -> (JoinHandle<T::Output>, Option<Notified<S>>)
where
S: Schedule,
T: Future + Send +'static,
T::Output: Send +'static,
{
let (task, notified, join) = super::new_task(task, scheduler);
unsafe {
// safety: We just created the task, so we have exclusive access
// to the field.
task.header().set_owner_id(self.id);
}
let mut lock = self.inner.lock();
if lock.closed {
drop(lock);
drop(notified);
task.shutdown();
(join, None)
} else {
lock.list.push_front(task);
(join, Some(notified))
}
}
/// Asserts that the given task is owned by this OwnedTasks and convert it to
/// a LocalNotified, giving the thread permission to poll this task.
#[inline]
pub(crate) fn assert_owner(&self, task: Notified<S>) -> LocalNotified<S> {
assert_eq!(task.header().get_owner_id(), self.id);
// safety: All tasks bound to this OwnedTasks are Send, so it is safe
// to poll it on this thread no matter what thread we are on.
LocalNotified {
task: task.0,
_not_send: PhantomData,
}
}
/// Shuts down all tasks in the collection. This call also closes the
/// collection, preventing new items from being added.
pub(crate) fn close_and_shutdown_all(&self)
where
S: Schedule,
{
// The first iteration of the loop was unrolled so it can set the
// closed bool.
let first_task = {
let mut lock = self.inner.lock();
lock.closed = true;
lock.list.pop_back()
};
match first_task {
Some(task) => task.shutdown(),
None => return,
}
loop {
let task = match self.inner.lock().list.pop_back() {
Some(task) => task,
None => return,
};
task.shutdown();
}
}
pub(crate) fn remove(&self, task: &Task<S>) -> Option<Task<S>> {
let task_id = task.header().get_owner_id();
if task_id == 0 {
// The task is unowned.
return None;
}
assert_eq!(task_id, self.id);
// safety: We just checked that the provided task is not in some other
// linked list.
unsafe { self.inner.lock().list.remove(task.header().into()) }
}
pub(crate) fn is_empty(&self) -> bool {
self.inner.lock().list.is_empty()
}
}
impl<S:'static> LocalOwnedTasks<S> {
pub(crate) fn new() -> Self {
Self {
inner: UnsafeCell::new(OwnedTasksInner {
list: LinkedList::new(),
closed: false,
}),
id: get_next_id(),
_not_send_or_sync: PhantomData,
}
}
pub(crate) fn bind<T>(
&self,
task: T,
scheduler: S,
) -> (JoinHandle<T::Output>, Option<Notified<S>>)
where
S: Schedule,
T: Future +'static,
T::Output:'static,
{
let (task, notified, join) = super::new_task(task, scheduler);
unsafe {
// safety: We just created the task, so we have exclusive access
// to the field.
task.header().set_owner_id(self.id);
}
if self.is_closed() {
drop(notified);
task.shutdown();
(join, None)
} else {
self.with_inner(|inner| {
inner.list.push_front(task);
});
(join, Some(notified))
}
}
/// Shuts down all tasks in the collection. This call also closes the
/// collection, preventing new items from being added.
pub(crate) fn close_and_shutdown_all(&self)
where
S: Schedule,
{
self.with_inner(|inner| inner.closed = true);
while let Some(task) = self.with_inner(|inner| inner.list.pop_back()) {
task.shutdown();
}
}
pub(crate) fn remove(&self, task: &Task<S>) -> Option<Task<S>> {
let task_id = task.header().get_owner_id();
if task_id == 0 {
// The task is unowned.
return None;
}
assert_eq!(task_id, self.id);
self.with_inner(|inner|
// safety: We just checked that the provided task is not in some
// other linked list.
unsafe { inner.list.remove(task.header().into()) }) | /// it to a LocalNotified, giving the thread permission to poll this task.
#[inline]
pub(crate) fn assert_owner(&self, task: Notified<S>) -> LocalNotified<S> {
assert_eq!(task.header().get_owner_id(), self.id);
// safety: The task was bound to this LocalOwnedTasks, and the
// LocalOwnedTasks is not Send or Sync, so we are on the right thread
// for polling this task.
LocalNotified {
task: task.0,
_not_send: PhantomData,
}
}
#[inline]
fn with_inner<F, T>(&self, f: F) -> T
where
F: FnOnce(&mut OwnedTasksInner<S>) -> T,
{
// safety: This type is not Sync, so concurrent calls of this method
// can't happen. Furthermore, all uses of this method in this file make
// sure that they don't call `with_inner` recursively.
self.inner.with_mut(|ptr| unsafe { f(&mut *ptr) })
}
pub(crate) fn is_closed(&self) -> bool {
self.with_inner(|inner| inner.closed)
}
pub(crate) fn is_empty(&self) -> bool {
self.with_inner(|inner| inner.list.is_empty())
}
}
#[cfg(all(test))]
mod tests {
use super::*;
// This test may run in parallel with other tests, so we only test that ids
// come in increasing order.
#[test]
fn test_id_not_broken() {
let mut last_id = get_next_id();
assert_ne!(last_id, 0);
for _ in 0..1000 {
let next_id = get_next_id();
assert_ne!(next_id, 0);
assert!(last_id < next_id);
last_id = next_id;
}
}
} | }
/// Asserts that the given task is owned by this LocalOwnedTasks and convert | random_line_split |
dst-dtor-1.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at | // 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.
static mut DROP_RAN: bool = false;
struct Foo;
impl Drop for Foo {
fn drop(&mut self) {
unsafe { DROP_RAN = true; }
}
}
trait Trait { fn dummy(&self) { } }
impl Trait for Foo {}
struct Fat<T:?Sized> {
f: T
}
pub fn main() {
{
// FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
let _x: Box<Fat<Trait>> = Box::<Fat<Foo>>::new(Fat { f: Foo });
}
unsafe {
assert!(DROP_RAN);
}
} | // http://rust-lang.org/COPYRIGHT.
// | random_line_split |
dst-dtor-1.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.
static mut DROP_RAN: bool = false;
struct Foo;
impl Drop for Foo {
fn drop(&mut self) {
unsafe { DROP_RAN = true; }
}
}
trait Trait { fn dummy(&self) { } }
impl Trait for Foo {}
struct Fat<T:?Sized> {
f: T
}
pub fn | () {
{
// FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
let _x: Box<Fat<Trait>> = Box::<Fat<Foo>>::new(Fat { f: Foo });
}
unsafe {
assert!(DROP_RAN);
}
}
| main | identifier_name |
dst-dtor-1.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.
static mut DROP_RAN: bool = false;
struct Foo;
impl Drop for Foo {
fn drop(&mut self) |
}
trait Trait { fn dummy(&self) { } }
impl Trait for Foo {}
struct Fat<T:?Sized> {
f: T
}
pub fn main() {
{
// FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
let _x: Box<Fat<Trait>> = Box::<Fat<Foo>>::new(Fat { f: Foo });
}
unsafe {
assert!(DROP_RAN);
}
}
| {
unsafe { DROP_RAN = true; }
} | identifier_body |
lib.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Do not remove on snapshot creation. Needed for bootstrap. (Issue #22364)
#![cfg_attr(stage0, feature(custom_attribute))] | #![unstable(feature = "rustc_private")]
#![staged_api]
#![crate_type = "dylib"]
#![crate_type = "rlib"]
#![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
html_favicon_url = "http://www.rust-lang.org/favicon.ico",
html_root_url = "http://doc.rust-lang.org/nightly/")]
#![allow(non_camel_case_types)]
#![feature(quote)]
#![feature(rustc_diagnostic_macros)]
#![feature(rustc_private)]
#![feature(staged_api)]
#![feature(into_cow)]
#[macro_use] extern crate log;
#[macro_use] extern crate syntax;
// for "clarity", rename the graphviz crate to dot; graphviz within `borrowck`
// refers to the borrowck-specific graphviz adapter traits.
extern crate graphviz as dot;
extern crate rustc;
pub use borrowck::check_crate;
pub use borrowck::build_borrowck_dataflow_data_for_fn;
pub use borrowck::FnPartsWithCFG;
// NB: This module needs to be declared first so diagnostics are
// registered before they are used.
pub mod diagnostics;
mod borrowck;
pub mod graphviz;
#[cfg(stage0)]
__build_diagnostic_array! { DIAGNOSTICS }
#[cfg(not(stage0))]
__build_diagnostic_array! { librustc_borrowck, DIAGNOSTICS } | #![crate_name = "rustc_borrowck"] | random_line_split |
qquote.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// ignore-pretty
// ignore-test
#![feature(quote)]
extern crate syntax;
use std::io::*;
use syntax::diagnostic;
use syntax::ast;
use syntax::codemap;
use syntax::codemap::span;
use syntax::parse;
use syntax::print::*;
trait fake_ext_ctxt {
fn cfg() -> ast::CrateConfig;
fn parse_sess() -> parse::parse_sess;
fn call_site() -> span;
fn ident_of(st: &str) -> ast::ident;
}
type fake_session = parse::parse_sess;
impl fake_ext_ctxt for fake_session {
fn cfg() -> ast::CrateConfig { Vec::new() }
fn parse_sess() -> parse::parse_sess { self }
fn call_site() -> span {
codemap::span {
lo: codemap::BytePos(0),
hi: codemap::BytePos(0),
expn_info: None
}
}
fn ident_of(st: &str) -> ast::ident {
self.interner.intern(st)
}
}
fn mk_ctxt() -> fake_ext_ctxt {
parse::new_parse_sess(None) as fake_ext_ctxt
}
fn main() {
let cx = mk_ctxt();
let abc = quote_expr!(cx, 23);
check_pp(ext_cx, abc, pprust::print_expr, "23".to_owned());
let ty = quote_ty!(cx, int);
check_pp(ext_cx, ty, pprust::print_type, "int".to_owned());
let item = quote_item!(cx, static x : int = 10;).get();
check_pp(ext_cx, item, pprust::print_item, "static x: int = 10;".to_owned());
let stmt = quote_stmt!(cx, let x = 20;);
check_pp(ext_cx, *stmt, pprust::print_stmt, "let x = 20;".to_owned());
let pat = quote_pat!(cx, Some(_));
check_pp(ext_cx, pat, pprust::print_pat, "Some(_)".to_owned());
| expr: T, f: |pprust::ps, T|, expect: StrBuf) {
let s = io::with_str_writer(|wr| {
let pp = pprust::rust_printer(wr, cx.parse_sess().interner);
f(pp, expr);
pp::eof(pp.s);
});
stdout().write_line(s);
if expect!= "".to_owned() {
println!("expect: '%s', got: '%s'", expect, s);
assert_eq!(s, expect);
}
} | }
fn check_pp<T>(cx: fake_ext_ctxt, | random_line_split |
qquote.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// ignore-pretty
// ignore-test
#![feature(quote)]
extern crate syntax;
use std::io::*;
use syntax::diagnostic;
use syntax::ast;
use syntax::codemap;
use syntax::codemap::span;
use syntax::parse;
use syntax::print::*;
trait fake_ext_ctxt {
fn cfg() -> ast::CrateConfig;
fn parse_sess() -> parse::parse_sess;
fn call_site() -> span;
fn ident_of(st: &str) -> ast::ident;
}
type fake_session = parse::parse_sess;
impl fake_ext_ctxt for fake_session {
fn cfg() -> ast::CrateConfig { Vec::new() }
fn parse_sess() -> parse::parse_sess |
fn call_site() -> span {
codemap::span {
lo: codemap::BytePos(0),
hi: codemap::BytePos(0),
expn_info: None
}
}
fn ident_of(st: &str) -> ast::ident {
self.interner.intern(st)
}
}
fn mk_ctxt() -> fake_ext_ctxt {
parse::new_parse_sess(None) as fake_ext_ctxt
}
fn main() {
let cx = mk_ctxt();
let abc = quote_expr!(cx, 23);
check_pp(ext_cx, abc, pprust::print_expr, "23".to_owned());
let ty = quote_ty!(cx, int);
check_pp(ext_cx, ty, pprust::print_type, "int".to_owned());
let item = quote_item!(cx, static x : int = 10;).get();
check_pp(ext_cx, item, pprust::print_item, "static x: int = 10;".to_owned());
let stmt = quote_stmt!(cx, let x = 20;);
check_pp(ext_cx, *stmt, pprust::print_stmt, "let x = 20;".to_owned());
let pat = quote_pat!(cx, Some(_));
check_pp(ext_cx, pat, pprust::print_pat, "Some(_)".to_owned());
}
fn check_pp<T>(cx: fake_ext_ctxt,
expr: T, f: |pprust::ps, T|, expect: StrBuf) {
let s = io::with_str_writer(|wr| {
let pp = pprust::rust_printer(wr, cx.parse_sess().interner);
f(pp, expr);
pp::eof(pp.s);
});
stdout().write_line(s);
if expect!= "".to_owned() {
println!("expect: '%s', got: '%s'", expect, s);
assert_eq!(s, expect);
}
}
| { self } | identifier_body |
qquote.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// ignore-pretty
// ignore-test
#![feature(quote)]
extern crate syntax;
use std::io::*;
use syntax::diagnostic;
use syntax::ast;
use syntax::codemap;
use syntax::codemap::span;
use syntax::parse;
use syntax::print::*;
trait fake_ext_ctxt {
fn cfg() -> ast::CrateConfig;
fn parse_sess() -> parse::parse_sess;
fn call_site() -> span;
fn ident_of(st: &str) -> ast::ident;
}
type fake_session = parse::parse_sess;
impl fake_ext_ctxt for fake_session {
fn cfg() -> ast::CrateConfig { Vec::new() }
fn parse_sess() -> parse::parse_sess { self }
fn call_site() -> span {
codemap::span {
lo: codemap::BytePos(0),
hi: codemap::BytePos(0),
expn_info: None
}
}
fn ident_of(st: &str) -> ast::ident {
self.interner.intern(st)
}
}
fn mk_ctxt() -> fake_ext_ctxt {
parse::new_parse_sess(None) as fake_ext_ctxt
}
fn | () {
let cx = mk_ctxt();
let abc = quote_expr!(cx, 23);
check_pp(ext_cx, abc, pprust::print_expr, "23".to_owned());
let ty = quote_ty!(cx, int);
check_pp(ext_cx, ty, pprust::print_type, "int".to_owned());
let item = quote_item!(cx, static x : int = 10;).get();
check_pp(ext_cx, item, pprust::print_item, "static x: int = 10;".to_owned());
let stmt = quote_stmt!(cx, let x = 20;);
check_pp(ext_cx, *stmt, pprust::print_stmt, "let x = 20;".to_owned());
let pat = quote_pat!(cx, Some(_));
check_pp(ext_cx, pat, pprust::print_pat, "Some(_)".to_owned());
}
fn check_pp<T>(cx: fake_ext_ctxt,
expr: T, f: |pprust::ps, T|, expect: StrBuf) {
let s = io::with_str_writer(|wr| {
let pp = pprust::rust_printer(wr, cx.parse_sess().interner);
f(pp, expr);
pp::eof(pp.s);
});
stdout().write_line(s);
if expect!= "".to_owned() {
println!("expect: '%s', got: '%s'", expect, s);
assert_eq!(s, expect);
}
}
| main | identifier_name |
qquote.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// ignore-pretty
// ignore-test
#![feature(quote)]
extern crate syntax;
use std::io::*;
use syntax::diagnostic;
use syntax::ast;
use syntax::codemap;
use syntax::codemap::span;
use syntax::parse;
use syntax::print::*;
trait fake_ext_ctxt {
fn cfg() -> ast::CrateConfig;
fn parse_sess() -> parse::parse_sess;
fn call_site() -> span;
fn ident_of(st: &str) -> ast::ident;
}
type fake_session = parse::parse_sess;
impl fake_ext_ctxt for fake_session {
fn cfg() -> ast::CrateConfig { Vec::new() }
fn parse_sess() -> parse::parse_sess { self }
fn call_site() -> span {
codemap::span {
lo: codemap::BytePos(0),
hi: codemap::BytePos(0),
expn_info: None
}
}
fn ident_of(st: &str) -> ast::ident {
self.interner.intern(st)
}
}
fn mk_ctxt() -> fake_ext_ctxt {
parse::new_parse_sess(None) as fake_ext_ctxt
}
fn main() {
let cx = mk_ctxt();
let abc = quote_expr!(cx, 23);
check_pp(ext_cx, abc, pprust::print_expr, "23".to_owned());
let ty = quote_ty!(cx, int);
check_pp(ext_cx, ty, pprust::print_type, "int".to_owned());
let item = quote_item!(cx, static x : int = 10;).get();
check_pp(ext_cx, item, pprust::print_item, "static x: int = 10;".to_owned());
let stmt = quote_stmt!(cx, let x = 20;);
check_pp(ext_cx, *stmt, pprust::print_stmt, "let x = 20;".to_owned());
let pat = quote_pat!(cx, Some(_));
check_pp(ext_cx, pat, pprust::print_pat, "Some(_)".to_owned());
}
fn check_pp<T>(cx: fake_ext_ctxt,
expr: T, f: |pprust::ps, T|, expect: StrBuf) {
let s = io::with_str_writer(|wr| {
let pp = pprust::rust_printer(wr, cx.parse_sess().interner);
f(pp, expr);
pp::eof(pp.s);
});
stdout().write_line(s);
if expect!= "".to_owned() |
}
| {
println!("expect: '%s', got: '%s'", expect, s);
assert_eq!(s, expect);
} | conditional_block |
borrowck-borrow-overloaded-auto-deref-mut.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 how overloaded deref interacts with borrows when DerefMut
// is implemented.
use std::ops::{Deref, DerefMut};
struct Own<T> {
value: *mut T
}
impl<T> Deref for Own<T> {
type Target = T;
fn deref(&self) -> &T {
unsafe { &*self.value }
}
}
impl<T> DerefMut for Own<T> {
fn deref_mut(&mut self) -> &mut T {
unsafe { &mut *self.value }
}
}
struct Point {
x: int,
y: int
}
impl Point {
fn get(&self) -> (int, int) {
(self.x, self.y)
}
fn set(&mut self, x: int, y: int) {
self.x = x;
self.y = y;
}
fn x_ref(&self) -> &int {
&self.x
}
fn y_mut(&mut self) -> &mut int {
&mut self.y
}
}
fn deref_imm_field(x: Own<Point>) {
let _i = &x.y;
}
fn deref_mut_field1(x: Own<Point>) {
let _i = &mut x.y; //~ ERROR cannot borrow
}
fn deref_mut_field2(mut x: Own<Point>) {
let _i = &mut x.y;
}
fn deref_extend_field(x: &Own<Point>) -> &int {
&x.y
}
fn deref_extend_mut_field1(x: &Own<Point>) -> &mut int {
&mut x.y //~ ERROR cannot borrow
}
fn deref_extend_mut_field2(x: &mut Own<Point>) -> &mut int {
&mut x.y
}
fn deref_extend_mut_field3(x: &mut Own<Point>) {
// Hmm, this is unfortunate, because with box it would work,
// but it's presently the expected outcome. See `deref_extend_mut_field4`
// for the workaround.
let _x = &mut x.x;
let _y = &mut x.y; //~ ERROR cannot borrow
}
fn deref_extend_mut_field4<'a>(x: &'a mut Own<Point>) {
let p = &mut **x;
let _x = &mut p.x;
let _y = &mut p.y;
}
fn assign_field1<'a>(x: Own<Point>) {
x.y = 3; //~ ERROR cannot borrow
}
fn assign_field2<'a>(x: &'a Own<Point>) {
x.y = 3; //~ ERROR cannot assign
}
fn assign_field3<'a>(x: &'a mut Own<Point>) {
x.y = 3;
}
fn assign_field4<'a>(x: &'a mut Own<Point>) {
let _p: &mut Point = &mut **x;
x.y = 3; //~ ERROR cannot borrow
}
// FIXME(eddyb) #12825 This shouldn't attempt to call deref_mut.
/*
fn deref_imm_method(x: Own<Point>) {
let _i = x.get();
}
*/
fn deref_mut_method1(x: Own<Point>) {
x.set(0, 0); //~ ERROR cannot borrow
}
fn deref_mut_method2(mut x: Own<Point>) {
x.set(0, 0);
}
fn deref_extend_method(x: &Own<Point>) -> &int {
x.x_ref()
}
fn deref_extend_mut_method1(x: &Own<Point>) -> &mut int {
x.y_mut() //~ ERROR cannot borrow
}
fn deref_extend_mut_method2(x: &mut Own<Point>) -> &mut int {
x.y_mut()
}
fn assign_method1<'a>(x: Own<Point>) {
*x.y_mut() = 3; //~ ERROR cannot borrow
}
fn assign_method2<'a>(x: &'a Own<Point>) {
*x.y_mut() = 3; //~ ERROR cannot borrow
}
fn assign_method3<'a>(x: &'a mut Own<Point>) |
pub fn main() {}
| {
*x.y_mut() = 3;
} | identifier_body |
borrowck-borrow-overloaded-auto-deref-mut.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 how overloaded deref interacts with borrows when DerefMut
// is implemented.
use std::ops::{Deref, DerefMut};
struct Own<T> {
value: *mut T
}
impl<T> Deref for Own<T> {
type Target = T;
fn deref(&self) -> &T {
unsafe { &*self.value }
}
}
impl<T> DerefMut for Own<T> {
fn deref_mut(&mut self) -> &mut T {
unsafe { &mut *self.value }
}
}
struct Point {
x: int,
y: int
}
impl Point {
fn get(&self) -> (int, int) {
(self.x, self.y)
} | self.y = y;
}
fn x_ref(&self) -> &int {
&self.x
}
fn y_mut(&mut self) -> &mut int {
&mut self.y
}
}
fn deref_imm_field(x: Own<Point>) {
let _i = &x.y;
}
fn deref_mut_field1(x: Own<Point>) {
let _i = &mut x.y; //~ ERROR cannot borrow
}
fn deref_mut_field2(mut x: Own<Point>) {
let _i = &mut x.y;
}
fn deref_extend_field(x: &Own<Point>) -> &int {
&x.y
}
fn deref_extend_mut_field1(x: &Own<Point>) -> &mut int {
&mut x.y //~ ERROR cannot borrow
}
fn deref_extend_mut_field2(x: &mut Own<Point>) -> &mut int {
&mut x.y
}
fn deref_extend_mut_field3(x: &mut Own<Point>) {
// Hmm, this is unfortunate, because with box it would work,
// but it's presently the expected outcome. See `deref_extend_mut_field4`
// for the workaround.
let _x = &mut x.x;
let _y = &mut x.y; //~ ERROR cannot borrow
}
fn deref_extend_mut_field4<'a>(x: &'a mut Own<Point>) {
let p = &mut **x;
let _x = &mut p.x;
let _y = &mut p.y;
}
fn assign_field1<'a>(x: Own<Point>) {
x.y = 3; //~ ERROR cannot borrow
}
fn assign_field2<'a>(x: &'a Own<Point>) {
x.y = 3; //~ ERROR cannot assign
}
fn assign_field3<'a>(x: &'a mut Own<Point>) {
x.y = 3;
}
fn assign_field4<'a>(x: &'a mut Own<Point>) {
let _p: &mut Point = &mut **x;
x.y = 3; //~ ERROR cannot borrow
}
// FIXME(eddyb) #12825 This shouldn't attempt to call deref_mut.
/*
fn deref_imm_method(x: Own<Point>) {
let _i = x.get();
}
*/
fn deref_mut_method1(x: Own<Point>) {
x.set(0, 0); //~ ERROR cannot borrow
}
fn deref_mut_method2(mut x: Own<Point>) {
x.set(0, 0);
}
fn deref_extend_method(x: &Own<Point>) -> &int {
x.x_ref()
}
fn deref_extend_mut_method1(x: &Own<Point>) -> &mut int {
x.y_mut() //~ ERROR cannot borrow
}
fn deref_extend_mut_method2(x: &mut Own<Point>) -> &mut int {
x.y_mut()
}
fn assign_method1<'a>(x: Own<Point>) {
*x.y_mut() = 3; //~ ERROR cannot borrow
}
fn assign_method2<'a>(x: &'a Own<Point>) {
*x.y_mut() = 3; //~ ERROR cannot borrow
}
fn assign_method3<'a>(x: &'a mut Own<Point>) {
*x.y_mut() = 3;
}
pub fn main() {} |
fn set(&mut self, x: int, y: int) {
self.x = x; | random_line_split |
borrowck-borrow-overloaded-auto-deref-mut.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 how overloaded deref interacts with borrows when DerefMut
// is implemented.
use std::ops::{Deref, DerefMut};
struct Own<T> {
value: *mut T
}
impl<T> Deref for Own<T> {
type Target = T;
fn deref(&self) -> &T {
unsafe { &*self.value }
}
}
impl<T> DerefMut for Own<T> {
fn deref_mut(&mut self) -> &mut T {
unsafe { &mut *self.value }
}
}
struct Point {
x: int,
y: int
}
impl Point {
fn get(&self) -> (int, int) {
(self.x, self.y)
}
fn set(&mut self, x: int, y: int) {
self.x = x;
self.y = y;
}
fn x_ref(&self) -> &int {
&self.x
}
fn y_mut(&mut self) -> &mut int {
&mut self.y
}
}
fn deref_imm_field(x: Own<Point>) {
let _i = &x.y;
}
fn deref_mut_field1(x: Own<Point>) {
let _i = &mut x.y; //~ ERROR cannot borrow
}
fn deref_mut_field2(mut x: Own<Point>) {
let _i = &mut x.y;
}
fn deref_extend_field(x: &Own<Point>) -> &int {
&x.y
}
fn deref_extend_mut_field1(x: &Own<Point>) -> &mut int {
&mut x.y //~ ERROR cannot borrow
}
fn deref_extend_mut_field2(x: &mut Own<Point>) -> &mut int {
&mut x.y
}
fn deref_extend_mut_field3(x: &mut Own<Point>) {
// Hmm, this is unfortunate, because with box it would work,
// but it's presently the expected outcome. See `deref_extend_mut_field4`
// for the workaround.
let _x = &mut x.x;
let _y = &mut x.y; //~ ERROR cannot borrow
}
fn deref_extend_mut_field4<'a>(x: &'a mut Own<Point>) {
let p = &mut **x;
let _x = &mut p.x;
let _y = &mut p.y;
}
fn assign_field1<'a>(x: Own<Point>) {
x.y = 3; //~ ERROR cannot borrow
}
fn assign_field2<'a>(x: &'a Own<Point>) {
x.y = 3; //~ ERROR cannot assign
}
fn assign_field3<'a>(x: &'a mut Own<Point>) {
x.y = 3;
}
fn assign_field4<'a>(x: &'a mut Own<Point>) {
let _p: &mut Point = &mut **x;
x.y = 3; //~ ERROR cannot borrow
}
// FIXME(eddyb) #12825 This shouldn't attempt to call deref_mut.
/*
fn deref_imm_method(x: Own<Point>) {
let _i = x.get();
}
*/
fn deref_mut_method1(x: Own<Point>) {
x.set(0, 0); //~ ERROR cannot borrow
}
fn deref_mut_method2(mut x: Own<Point>) {
x.set(0, 0);
}
fn deref_extend_method(x: &Own<Point>) -> &int {
x.x_ref()
}
fn deref_extend_mut_method1(x: &Own<Point>) -> &mut int {
x.y_mut() //~ ERROR cannot borrow
}
fn deref_extend_mut_method2(x: &mut Own<Point>) -> &mut int {
x.y_mut()
}
fn assign_method1<'a>(x: Own<Point>) {
*x.y_mut() = 3; //~ ERROR cannot borrow
}
fn | <'a>(x: &'a Own<Point>) {
*x.y_mut() = 3; //~ ERROR cannot borrow
}
fn assign_method3<'a>(x: &'a mut Own<Point>) {
*x.y_mut() = 3;
}
pub fn main() {}
| assign_method2 | identifier_name |
size_of_tests.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use cssparser::ToCss;
use gecko_like_types;
use gecko_like_types::*;
use parser;
use parser::*;
use precomputed_hash::PrecomputedHash;
use std::fmt;
use visitor::SelectorVisitor;
size_of_test!(size_of_selector, Selector<Impl>, 48);
size_of_test!(size_of_pseudo_element, gecko_like_types::PseudoElement, 1);
size_of_test!(size_of_selector_inner, SelectorInner<Impl>, 40);
size_of_test!(size_of_complex_selector, ComplexSelector<Impl>, 24);
size_of_test!(size_of_component, Component<Impl>, 32);
size_of_test!(size_of_pseudo_class, PseudoClass, 24);
impl parser::PseudoElement for gecko_like_types::PseudoElement {
type Impl = Impl;
}
// Boilerplate
impl SelectorImpl for Impl {
type AttrValue = Atom;
type Identifier = Atom;
type ClassName = Atom;
type LocalName = Atom;
type NamespaceUrl = Atom;
type NamespacePrefix = Atom;
type BorrowedLocalName = Atom;
type BorrowedNamespaceUrl = Atom;
type NonTSPseudoClass = PseudoClass;
type PseudoElement = gecko_like_types::PseudoElement;
}
impl SelectorMethods for PseudoClass {
type Impl = Impl;
fn visit<V>(&self, _visitor: &mut V) -> bool
where V: SelectorVisitor<Impl = Self::Impl> { unimplemented!() }
}
impl ToCss for PseudoClass {
fn to_css<W>(&self, _: &mut W) -> fmt::Result where W: fmt::Write { unimplemented!() }
}
impl ToCss for gecko_like_types::PseudoElement {
fn to_css<W>(&self, _: &mut W) -> fmt::Result where W: fmt::Write { unimplemented!() }
}
impl fmt::Display for Atom {
fn fmt(&self, _: &mut fmt::Formatter) -> fmt::Result { unimplemented!() }
}
impl From<String> for Atom {
fn | (_: String) -> Self { unimplemented!() }
}
impl<'a> From<&'a str> for Atom {
fn from(_: &'a str) -> Self { unimplemented!() }
}
impl PrecomputedHash for Atom {
fn precomputed_hash(&self) -> u32 { unimplemented!() }
}
| from | identifier_name |
size_of_tests.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use cssparser::ToCss;
use gecko_like_types;
use gecko_like_types::*;
use parser;
use parser::*;
use precomputed_hash::PrecomputedHash;
use std::fmt;
use visitor::SelectorVisitor;
size_of_test!(size_of_selector, Selector<Impl>, 48);
size_of_test!(size_of_pseudo_element, gecko_like_types::PseudoElement, 1);
size_of_test!(size_of_selector_inner, SelectorInner<Impl>, 40);
size_of_test!(size_of_complex_selector, ComplexSelector<Impl>, 24);
size_of_test!(size_of_component, Component<Impl>, 32);
size_of_test!(size_of_pseudo_class, PseudoClass, 24);
impl parser::PseudoElement for gecko_like_types::PseudoElement {
type Impl = Impl;
}
// Boilerplate
impl SelectorImpl for Impl {
type AttrValue = Atom;
type Identifier = Atom;
type ClassName = Atom;
type LocalName = Atom;
type NamespaceUrl = Atom;
type NamespacePrefix = Atom;
type BorrowedLocalName = Atom;
type BorrowedNamespaceUrl = Atom;
type NonTSPseudoClass = PseudoClass;
type PseudoElement = gecko_like_types::PseudoElement;
}
impl SelectorMethods for PseudoClass {
type Impl = Impl;
fn visit<V>(&self, _visitor: &mut V) -> bool
where V: SelectorVisitor<Impl = Self::Impl> { unimplemented!() }
}
impl ToCss for PseudoClass {
fn to_css<W>(&self, _: &mut W) -> fmt::Result where W: fmt::Write { unimplemented!() }
}
impl ToCss for gecko_like_types::PseudoElement {
fn to_css<W>(&self, _: &mut W) -> fmt::Result where W: fmt::Write { unimplemented!() }
}
impl fmt::Display for Atom {
fn fmt(&self, _: &mut fmt::Formatter) -> fmt::Result { unimplemented!() }
}
impl From<String> for Atom {
fn from(_: String) -> Self |
}
impl<'a> From<&'a str> for Atom {
fn from(_: &'a str) -> Self { unimplemented!() }
}
impl PrecomputedHash for Atom {
fn precomputed_hash(&self) -> u32 { unimplemented!() }
}
| { unimplemented!() } | identifier_body |
size_of_tests.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use cssparser::ToCss;
use gecko_like_types;
use gecko_like_types::*;
use parser;
use parser::*;
use precomputed_hash::PrecomputedHash;
use std::fmt; | size_of_test!(size_of_selector_inner, SelectorInner<Impl>, 40);
size_of_test!(size_of_complex_selector, ComplexSelector<Impl>, 24);
size_of_test!(size_of_component, Component<Impl>, 32);
size_of_test!(size_of_pseudo_class, PseudoClass, 24);
impl parser::PseudoElement for gecko_like_types::PseudoElement {
type Impl = Impl;
}
// Boilerplate
impl SelectorImpl for Impl {
type AttrValue = Atom;
type Identifier = Atom;
type ClassName = Atom;
type LocalName = Atom;
type NamespaceUrl = Atom;
type NamespacePrefix = Atom;
type BorrowedLocalName = Atom;
type BorrowedNamespaceUrl = Atom;
type NonTSPseudoClass = PseudoClass;
type PseudoElement = gecko_like_types::PseudoElement;
}
impl SelectorMethods for PseudoClass {
type Impl = Impl;
fn visit<V>(&self, _visitor: &mut V) -> bool
where V: SelectorVisitor<Impl = Self::Impl> { unimplemented!() }
}
impl ToCss for PseudoClass {
fn to_css<W>(&self, _: &mut W) -> fmt::Result where W: fmt::Write { unimplemented!() }
}
impl ToCss for gecko_like_types::PseudoElement {
fn to_css<W>(&self, _: &mut W) -> fmt::Result where W: fmt::Write { unimplemented!() }
}
impl fmt::Display for Atom {
fn fmt(&self, _: &mut fmt::Formatter) -> fmt::Result { unimplemented!() }
}
impl From<String> for Atom {
fn from(_: String) -> Self { unimplemented!() }
}
impl<'a> From<&'a str> for Atom {
fn from(_: &'a str) -> Self { unimplemented!() }
}
impl PrecomputedHash for Atom {
fn precomputed_hash(&self) -> u32 { unimplemented!() }
} | use visitor::SelectorVisitor;
size_of_test!(size_of_selector, Selector<Impl>, 48);
size_of_test!(size_of_pseudo_element, gecko_like_types::PseudoElement, 1); | random_line_split |
compl.rs | use std::env;
use std::fs;
use sym::Symtable;
extern crate glob;
fn common_prefix(mut strs: Vec<String>) -> String {
let mut c_prefix = String::new();
if strs.len() == 0 {
return c_prefix;
}
let delegate = strs.pop().unwrap().clone();
for (di, dc) in delegate.chars().enumerate() {
for ostr in &strs {
match ostr.chars().nth(di) {
Some(oc) => {
if dc!= oc {
return c_prefix;
}
}
None => {
return c_prefix;
}
}
}
c_prefix.push(dc);
}
c_prefix
}
fn print_completions(res_vec: &Vec<String>) {
// TODO: prettier
println!("");
for p in res_vec {
println!("{}", p);
}
}
pub fn | (in_str: &str, st: &Symtable, first_word: bool, print_multi: bool) -> String {
if first_word &&!in_str.contains('/') {
bin_complete(in_str, st, print_multi)
} else {
fs_complete(in_str, print_multi)
}
}
pub fn bin_complete(in_str: &str, st: &Symtable, print_multi: bool) -> String {
let res_vec = st.prefix_resolve_exec(in_str);
if res_vec.len() == 1 {
let mut res = res_vec[0].clone();
res.push(' ');
res
} else if res_vec.len() == 0 {
in_str.to_string()
} else {
if print_multi {
print_completions(&res_vec);
}
common_prefix(res_vec)
}
}
// TODO: more completely handle globs in the to-complete string
pub fn fs_complete(in_str: &str, print_multi: bool) -> String {
let mut input;
let mut tilde = false;
let mut cpref = false;
if in_str.starts_with("~/") {
tilde = true;
let in_str = in_str.trim_left_matches("~");
input = env::var("HOME").unwrap_or("~/".to_string());
input.push_str(in_str);
} else {
if in_str.starts_with("./") {
cpref = true;
}
input = in_str.to_string();
}
if!input.ends_with('*') {
input.push('*');
}
let mut postfix = "";
let res_vec = match glob::glob(&input) {
Ok(x) => x,
Err(_) => {
return in_str.to_string();
}
}
.filter_map(Result::ok)
.map(|x| format!("{}", x.display()))
.collect::<Vec<String>>();
let mut ret = if res_vec.len() == 1 {
let ref res = res_vec[0];
postfix = match fs::metadata(res) {
Ok(x) => {
if x.is_dir() {
"/"
} else {
" "
}
}
Err(_) => "",
};
res.clone()
} else if res_vec.len() > 0 {
if print_multi {
print_completions(&res_vec);
}
// find common prefix
common_prefix(res_vec)
} else {
in_str.to_string()
};
// post-facto formatting
ret = ret.replace(" ", "\\ ");
ret.push_str(postfix);
if tilde {
ret.replace(&env::var("HOME").unwrap(), "~")
} else {
if cpref &&!ret.starts_with("./") {
ret.insert(0, '.');
ret.insert(1, '/');
}
ret
}
}
| complete | identifier_name |
compl.rs | use std::env;
use std::fs;
use sym::Symtable;
extern crate glob;
fn common_prefix(mut strs: Vec<String>) -> String {
let mut c_prefix = String::new();
if strs.len() == 0 {
return c_prefix;
}
let delegate = strs.pop().unwrap().clone();
for (di, dc) in delegate.chars().enumerate() {
for ostr in &strs {
match ostr.chars().nth(di) {
Some(oc) => |
None => {
return c_prefix;
}
}
}
c_prefix.push(dc);
}
c_prefix
}
fn print_completions(res_vec: &Vec<String>) {
// TODO: prettier
println!("");
for p in res_vec {
println!("{}", p);
}
}
pub fn complete(in_str: &str, st: &Symtable, first_word: bool, print_multi: bool) -> String {
if first_word &&!in_str.contains('/') {
bin_complete(in_str, st, print_multi)
} else {
fs_complete(in_str, print_multi)
}
}
pub fn bin_complete(in_str: &str, st: &Symtable, print_multi: bool) -> String {
let res_vec = st.prefix_resolve_exec(in_str);
if res_vec.len() == 1 {
let mut res = res_vec[0].clone();
res.push(' ');
res
} else if res_vec.len() == 0 {
in_str.to_string()
} else {
if print_multi {
print_completions(&res_vec);
}
common_prefix(res_vec)
}
}
// TODO: more completely handle globs in the to-complete string
pub fn fs_complete(in_str: &str, print_multi: bool) -> String {
let mut input;
let mut tilde = false;
let mut cpref = false;
if in_str.starts_with("~/") {
tilde = true;
let in_str = in_str.trim_left_matches("~");
input = env::var("HOME").unwrap_or("~/".to_string());
input.push_str(in_str);
} else {
if in_str.starts_with("./") {
cpref = true;
}
input = in_str.to_string();
}
if!input.ends_with('*') {
input.push('*');
}
let mut postfix = "";
let res_vec = match glob::glob(&input) {
Ok(x) => x,
Err(_) => {
return in_str.to_string();
}
}
.filter_map(Result::ok)
.map(|x| format!("{}", x.display()))
.collect::<Vec<String>>();
let mut ret = if res_vec.len() == 1 {
let ref res = res_vec[0];
postfix = match fs::metadata(res) {
Ok(x) => {
if x.is_dir() {
"/"
} else {
" "
}
}
Err(_) => "",
};
res.clone()
} else if res_vec.len() > 0 {
if print_multi {
print_completions(&res_vec);
}
// find common prefix
common_prefix(res_vec)
} else {
in_str.to_string()
};
// post-facto formatting
ret = ret.replace(" ", "\\ ");
ret.push_str(postfix);
if tilde {
ret.replace(&env::var("HOME").unwrap(), "~")
} else {
if cpref &&!ret.starts_with("./") {
ret.insert(0, '.');
ret.insert(1, '/');
}
ret
}
}
| {
if dc != oc {
return c_prefix;
}
} | conditional_block |
compl.rs | use std::env;
use std::fs;
use sym::Symtable;
extern crate glob;
fn common_prefix(mut strs: Vec<String>) -> String {
let mut c_prefix = String::new();
if strs.len() == 0 {
return c_prefix;
}
let delegate = strs.pop().unwrap().clone();
for (di, dc) in delegate.chars().enumerate() {
for ostr in &strs {
match ostr.chars().nth(di) {
Some(oc) => {
if dc!= oc {
return c_prefix;
}
}
None => {
return c_prefix;
}
}
}
c_prefix.push(dc);
}
c_prefix
}
fn print_completions(res_vec: &Vec<String>) |
pub fn complete(in_str: &str, st: &Symtable, first_word: bool, print_multi: bool) -> String {
if first_word &&!in_str.contains('/') {
bin_complete(in_str, st, print_multi)
} else {
fs_complete(in_str, print_multi)
}
}
pub fn bin_complete(in_str: &str, st: &Symtable, print_multi: bool) -> String {
let res_vec = st.prefix_resolve_exec(in_str);
if res_vec.len() == 1 {
let mut res = res_vec[0].clone();
res.push(' ');
res
} else if res_vec.len() == 0 {
in_str.to_string()
} else {
if print_multi {
print_completions(&res_vec);
}
common_prefix(res_vec)
}
}
// TODO: more completely handle globs in the to-complete string
pub fn fs_complete(in_str: &str, print_multi: bool) -> String {
let mut input;
let mut tilde = false;
let mut cpref = false;
if in_str.starts_with("~/") {
tilde = true;
let in_str = in_str.trim_left_matches("~");
input = env::var("HOME").unwrap_or("~/".to_string());
input.push_str(in_str);
} else {
if in_str.starts_with("./") {
cpref = true;
}
input = in_str.to_string();
}
if!input.ends_with('*') {
input.push('*');
}
let mut postfix = "";
let res_vec = match glob::glob(&input) {
Ok(x) => x,
Err(_) => {
return in_str.to_string();
}
}
.filter_map(Result::ok)
.map(|x| format!("{}", x.display()))
.collect::<Vec<String>>();
let mut ret = if res_vec.len() == 1 {
let ref res = res_vec[0];
postfix = match fs::metadata(res) {
Ok(x) => {
if x.is_dir() {
"/"
} else {
" "
}
}
Err(_) => "",
};
res.clone()
} else if res_vec.len() > 0 {
if print_multi {
print_completions(&res_vec);
}
// find common prefix
common_prefix(res_vec)
} else {
in_str.to_string()
};
// post-facto formatting
ret = ret.replace(" ", "\\ ");
ret.push_str(postfix);
if tilde {
ret.replace(&env::var("HOME").unwrap(), "~")
} else {
if cpref &&!ret.starts_with("./") {
ret.insert(0, '.');
ret.insert(1, '/');
}
ret
}
}
| {
// TODO: prettier
println!("");
for p in res_vec {
println!("{}", p);
}
} | identifier_body |
compl.rs | use std::env;
use std::fs;
use sym::Symtable;
extern crate glob;
fn common_prefix(mut strs: Vec<String>) -> String {
let mut c_prefix = String::new();
if strs.len() == 0 {
return c_prefix;
}
let delegate = strs.pop().unwrap().clone();
for (di, dc) in delegate.chars().enumerate() {
for ostr in &strs {
match ostr.chars().nth(di) {
Some(oc) => {
if dc!= oc {
return c_prefix;
}
}
None => {
return c_prefix;
}
}
}
c_prefix.push(dc);
}
c_prefix
}
fn print_completions(res_vec: &Vec<String>) {
// TODO: prettier
println!("");
for p in res_vec {
println!("{}", p);
} |
pub fn complete(in_str: &str, st: &Symtable, first_word: bool, print_multi: bool) -> String {
if first_word &&!in_str.contains('/') {
bin_complete(in_str, st, print_multi)
} else {
fs_complete(in_str, print_multi)
}
}
pub fn bin_complete(in_str: &str, st: &Symtable, print_multi: bool) -> String {
let res_vec = st.prefix_resolve_exec(in_str);
if res_vec.len() == 1 {
let mut res = res_vec[0].clone();
res.push(' ');
res
} else if res_vec.len() == 0 {
in_str.to_string()
} else {
if print_multi {
print_completions(&res_vec);
}
common_prefix(res_vec)
}
}
// TODO: more completely handle globs in the to-complete string
pub fn fs_complete(in_str: &str, print_multi: bool) -> String {
let mut input;
let mut tilde = false;
let mut cpref = false;
if in_str.starts_with("~/") {
tilde = true;
let in_str = in_str.trim_left_matches("~");
input = env::var("HOME").unwrap_or("~/".to_string());
input.push_str(in_str);
} else {
if in_str.starts_with("./") {
cpref = true;
}
input = in_str.to_string();
}
if!input.ends_with('*') {
input.push('*');
}
let mut postfix = "";
let res_vec = match glob::glob(&input) {
Ok(x) => x,
Err(_) => {
return in_str.to_string();
}
}
.filter_map(Result::ok)
.map(|x| format!("{}", x.display()))
.collect::<Vec<String>>();
let mut ret = if res_vec.len() == 1 {
let ref res = res_vec[0];
postfix = match fs::metadata(res) {
Ok(x) => {
if x.is_dir() {
"/"
} else {
" "
}
}
Err(_) => "",
};
res.clone()
} else if res_vec.len() > 0 {
if print_multi {
print_completions(&res_vec);
}
// find common prefix
common_prefix(res_vec)
} else {
in_str.to_string()
};
// post-facto formatting
ret = ret.replace(" ", "\\ ");
ret.push_str(postfix);
if tilde {
ret.replace(&env::var("HOME").unwrap(), "~")
} else {
if cpref &&!ret.starts_with("./") {
ret.insert(0, '.');
ret.insert(1, '/');
}
ret
}
} | } | random_line_split |
io.rs | //
// imag - the personal information management suite for the commandline
// Copyright (C) 2015-2020 Matthias Beyer <[email protected]> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; version
// 2.1 of the License.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
//
//! Proxy objects for std::io::Stdin, std::io::Stdout, std::io::Stderr
use std::fmt::Debug;
use std::io::Write;
/// Proxy object for output
///
/// This is returned by `Runtime::stdout()` does implement `Write`. So you can
/// `write!(rt.stdout(), "some things")` and it just works.
///
/// The `Runtime` has to decide whether the OutputProxy should write to stdout, stderr or simply be
/// a "sink" which does not write to either.
///
pub enum OutputProxy {
Out(::std::io::Stdout),
Err(::std::io::Stderr),
Sink,
}
impl Write for OutputProxy {
fn write(&mut self, buf: &[u8]) -> ::std::io::Result<usize> {
match *self {
OutputProxy::Out(ref mut r) => r.write(buf),
OutputProxy::Err(ref mut r) => r.write(buf),
OutputProxy::Sink => Ok(0),
}
}
fn flush(&mut self) -> ::std::io::Result<()> {
match *self {
OutputProxy::Out(ref mut r) => r.flush(),
OutputProxy::Err(ref mut r) => r.flush(),
OutputProxy::Sink => Ok(()),
}
}
}
impl Debug for OutputProxy {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> Result<(), ::std::fmt::Error> {
match *self {
OutputProxy::Out(..) => write!(f, "OutputProxy(Stdout)"),
OutputProxy::Err(..) => write!(f, "OutputProxy(Stderr)"),
OutputProxy::Sink => write!(f, "OutputProxy(Sink)"),
}
}
}
impl OutputProxy {
pub fn lock(&self) -> LockedOutputProxy {
match *self {
OutputProxy::Out(ref r) => LockedOutputProxy::Out(r.lock()),
OutputProxy::Err(ref r) => LockedOutputProxy::Err(r.lock()),
OutputProxy::Sink => LockedOutputProxy::Sink,
}
}
}
pub enum LockedOutputProxy<'a> {
Out(::std::io::StdoutLock<'a>),
Err(::std::io::StderrLock<'a>),
Sink,
}
impl<'a> Write for LockedOutputProxy<'a> {
fn | (&mut self, buf: &[u8]) -> ::std::io::Result<usize> {
match *self {
LockedOutputProxy::Out(ref mut r) => r.write(buf),
LockedOutputProxy::Err(ref mut r) => r.write(buf),
LockedOutputProxy::Sink => Ok(buf.len()),
}
}
fn flush(&mut self) -> ::std::io::Result<()> {
match *self {
LockedOutputProxy::Out(ref mut r) => r.flush(),
LockedOutputProxy::Err(ref mut r) => r.flush(),
LockedOutputProxy::Sink => Ok(()),
}
}
}
impl<'a> Debug for LockedOutputProxy<'a> {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> Result<(), ::std::fmt::Error> {
match *self {
LockedOutputProxy::Out(..) => write!(f, "LockedOutputProxy(Stdout)"),
LockedOutputProxy::Err(..) => write!(f, "LockedOutputProxy(Stderr)"),
LockedOutputProxy::Sink => write!(f, "LockedOutputProxy(Sink)"),
}
}
}
| write | identifier_name |
io.rs | //
// imag - the personal information management suite for the commandline
// Copyright (C) 2015-2020 Matthias Beyer <[email protected]> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; version
// 2.1 of the License.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
//
//! Proxy objects for std::io::Stdin, std::io::Stdout, std::io::Stderr
use std::fmt::Debug;
use std::io::Write;
/// Proxy object for output
///
/// This is returned by `Runtime::stdout()` does implement `Write`. So you can
/// `write!(rt.stdout(), "some things")` and it just works.
///
/// The `Runtime` has to decide whether the OutputProxy should write to stdout, stderr or simply be
/// a "sink" which does not write to either.
///
pub enum OutputProxy {
Out(::std::io::Stdout),
Err(::std::io::Stderr),
Sink,
}
impl Write for OutputProxy {
fn write(&mut self, buf: &[u8]) -> ::std::io::Result<usize> {
match *self {
OutputProxy::Out(ref mut r) => r.write(buf),
OutputProxy::Err(ref mut r) => r.write(buf),
OutputProxy::Sink => Ok(0),
}
}
fn flush(&mut self) -> ::std::io::Result<()> {
match *self {
OutputProxy::Out(ref mut r) => r.flush(),
OutputProxy::Err(ref mut r) => r.flush(), |
}
impl Debug for OutputProxy {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> Result<(), ::std::fmt::Error> {
match *self {
OutputProxy::Out(..) => write!(f, "OutputProxy(Stdout)"),
OutputProxy::Err(..) => write!(f, "OutputProxy(Stderr)"),
OutputProxy::Sink => write!(f, "OutputProxy(Sink)"),
}
}
}
impl OutputProxy {
pub fn lock(&self) -> LockedOutputProxy {
match *self {
OutputProxy::Out(ref r) => LockedOutputProxy::Out(r.lock()),
OutputProxy::Err(ref r) => LockedOutputProxy::Err(r.lock()),
OutputProxy::Sink => LockedOutputProxy::Sink,
}
}
}
pub enum LockedOutputProxy<'a> {
Out(::std::io::StdoutLock<'a>),
Err(::std::io::StderrLock<'a>),
Sink,
}
impl<'a> Write for LockedOutputProxy<'a> {
fn write(&mut self, buf: &[u8]) -> ::std::io::Result<usize> {
match *self {
LockedOutputProxy::Out(ref mut r) => r.write(buf),
LockedOutputProxy::Err(ref mut r) => r.write(buf),
LockedOutputProxy::Sink => Ok(buf.len()),
}
}
fn flush(&mut self) -> ::std::io::Result<()> {
match *self {
LockedOutputProxy::Out(ref mut r) => r.flush(),
LockedOutputProxy::Err(ref mut r) => r.flush(),
LockedOutputProxy::Sink => Ok(()),
}
}
}
impl<'a> Debug for LockedOutputProxy<'a> {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> Result<(), ::std::fmt::Error> {
match *self {
LockedOutputProxy::Out(..) => write!(f, "LockedOutputProxy(Stdout)"),
LockedOutputProxy::Err(..) => write!(f, "LockedOutputProxy(Stderr)"),
LockedOutputProxy::Sink => write!(f, "LockedOutputProxy(Sink)"),
}
}
} | OutputProxy::Sink => Ok(()),
}
} | random_line_split |
test.rs | use std::marker::PhantomData;
//TODO merge_left/merge_right/split_left/split_right for lifetimes
//TODO existentials: https://github.com/bluss/indexing
//This is a transparent wrapper over a slice, with two run-time type tags for the beginning and the
//end of the slice
pub struct SliceFragment<'a, T: 'a, A, B>(
pub &'a mut [T],
PhantomData<A>,
PhantomData<B>
);
impl<'a, T: 'a + Sized, A, B> SliceFragment<'a, T, A, B> {
//Creating an empty slice fragment, for demonstration purposes.
//Note that the beginning and end markers are the same.
pub fn empty(slice: &'a mut [T; 0]) -> SliceFragment<'a, T, A, A> {
SliceFragment(
slice,
PhantomData,
PhantomData
)
}
//Note that the type parameters A and B are user-provided; if they are the same, type safety
//goes out the window. A better version would use existential types.
pub fn new(slice: &'a mut [T]) -> SliceFragment<'a, T, A, B> |
}
//Merge is only allowed if the end marker of the first slice fragment coincides with the begin
//marker of the second slice fragment
pub fn merge<'a, 'b, 'c: 'a + 'b, T: 'a, A, B, C>(
SliceFragment(slice1, begin1, _): SliceFragment<'a, T, A, B>,
SliceFragment(slice2, _, end2) : SliceFragment<'b, T, B, C>
) -> SliceFragment<'c, T, A, C> {
unsafe {
let slice = std::slice::from_raw_parts_mut(slice1.as_mut_ptr(), slice1.len() + slice2.len());
SliceFragment(slice, begin1, end2)
}
}
//NOT TYPE SAFE if any of A, B or C are the same type
pub fn split<'a, T: 'a, A, B, C>(
SliceFragment(slice, begin1, end2): SliceFragment<'a, T, A, C>,
index: usize
) -> (SliceFragment<'a, T, A, B>, SliceFragment<'a, T, B, C>) {
let end1: PhantomData<B> = PhantomData;
let begin2: PhantomData<B> = PhantomData;
let (slice1, slice2) = slice.split_at_mut(index);
(
SliceFragment(slice1, begin1, end1),
SliceFragment(slice2, begin2, end2)
)
}
| {
SliceFragment(
slice,
PhantomData,
PhantomData
)
} | identifier_body |
test.rs | use std::marker::PhantomData;
//TODO merge_left/merge_right/split_left/split_right for lifetimes
//TODO existentials: https://github.com/bluss/indexing
//This is a transparent wrapper over a slice, with two run-time type tags for the beginning and the
//end of the slice
pub struct | <'a, T: 'a, A, B>(
pub &'a mut [T],
PhantomData<A>,
PhantomData<B>
);
impl<'a, T: 'a + Sized, A, B> SliceFragment<'a, T, A, B> {
//Creating an empty slice fragment, for demonstration purposes.
//Note that the beginning and end markers are the same.
pub fn empty(slice: &'a mut [T; 0]) -> SliceFragment<'a, T, A, A> {
SliceFragment(
slice,
PhantomData,
PhantomData
)
}
//Note that the type parameters A and B are user-provided; if they are the same, type safety
//goes out the window. A better version would use existential types.
pub fn new(slice: &'a mut [T]) -> SliceFragment<'a, T, A, B> {
SliceFragment(
slice,
PhantomData,
PhantomData
)
}
}
//Merge is only allowed if the end marker of the first slice fragment coincides with the begin
//marker of the second slice fragment
pub fn merge<'a, 'b, 'c: 'a + 'b, T: 'a, A, B, C>(
SliceFragment(slice1, begin1, _): SliceFragment<'a, T, A, B>,
SliceFragment(slice2, _, end2) : SliceFragment<'b, T, B, C>
) -> SliceFragment<'c, T, A, C> {
unsafe {
let slice = std::slice::from_raw_parts_mut(slice1.as_mut_ptr(), slice1.len() + slice2.len());
SliceFragment(slice, begin1, end2)
}
}
//NOT TYPE SAFE if any of A, B or C are the same type
pub fn split<'a, T: 'a, A, B, C>(
SliceFragment(slice, begin1, end2): SliceFragment<'a, T, A, C>,
index: usize
) -> (SliceFragment<'a, T, A, B>, SliceFragment<'a, T, B, C>) {
let end1: PhantomData<B> = PhantomData;
let begin2: PhantomData<B> = PhantomData;
let (slice1, slice2) = slice.split_at_mut(index);
(
SliceFragment(slice1, begin1, end1),
SliceFragment(slice2, begin2, end2)
)
}
| SliceFragment | identifier_name |
test.rs | use std::marker::PhantomData;
//TODO merge_left/merge_right/split_left/split_right for lifetimes
//TODO existentials: https://github.com/bluss/indexing
//This is a transparent wrapper over a slice, with two run-time type tags for the beginning and the
//end of the slice
pub struct SliceFragment<'a, T: 'a, A, B>(
pub &'a mut [T],
PhantomData<A>,
PhantomData<B>
);
impl<'a, T: 'a + Sized, A, B> SliceFragment<'a, T, A, B> {
//Creating an empty slice fragment, for demonstration purposes.
//Note that the beginning and end markers are the same.
pub fn empty(slice: &'a mut [T; 0]) -> SliceFragment<'a, T, A, A> {
SliceFragment(
slice,
PhantomData,
PhantomData
)
}
//Note that the type parameters A and B are user-provided; if they are the same, type safety
//goes out the window. A better version would use existential types.
pub fn new(slice: &'a mut [T]) -> SliceFragment<'a, T, A, B> {
SliceFragment(
slice,
PhantomData,
PhantomData
)
}
}
//Merge is only allowed if the end marker of the first slice fragment coincides with the begin
//marker of the second slice fragment
pub fn merge<'a, 'b, 'c: 'a + 'b, T: 'a, A, B, C>(
SliceFragment(slice1, begin1, _): SliceFragment<'a, T, A, B>,
SliceFragment(slice2, _, end2) : SliceFragment<'b, T, B, C>
) -> SliceFragment<'c, T, A, C> {
unsafe {
let slice = std::slice::from_raw_parts_mut(slice1.as_mut_ptr(), slice1.len() + slice2.len());
SliceFragment(slice, begin1, end2)
} | pub fn split<'a, T: 'a, A, B, C>(
SliceFragment(slice, begin1, end2): SliceFragment<'a, T, A, C>,
index: usize
) -> (SliceFragment<'a, T, A, B>, SliceFragment<'a, T, B, C>) {
let end1: PhantomData<B> = PhantomData;
let begin2: PhantomData<B> = PhantomData;
let (slice1, slice2) = slice.split_at_mut(index);
(
SliceFragment(slice1, begin1, end1),
SliceFragment(slice2, begin2, end2)
)
} | }
//NOT TYPE SAFE if any of A, B or C are the same type | random_line_split |
cors_cache.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/. */
//! An implementation of the [CORS preflight cache](https://fetch.spec.whatwg.org/#cors-preflight-cache)
//! For now this library is XHR-specific.
//! For stuff involving `<img>`, `<iframe>`, `<form>`, etc please check what
//! the request mode should be and compare with the fetch spec
//! This library will eventually become the core of the Fetch crate
//! with CORSRequest being expanded into FetchRequest (etc)
use hyper::method::Method;
use net_traits::request::{CredentialsMode, Origin, Request};
use servo_url::ServoUrl;
use std::ascii::AsciiExt;
use time::{self, Timespec};
/// Union type for CORS cache entries
///
/// Each entry might pertain to a header or method
#[derive(Clone, Debug)]
pub enum HeaderOrMethod {
HeaderData(String),
MethodData(Method)
}
impl HeaderOrMethod {
fn match_header(&self, header_name: &str) -> bool {
match *self {
HeaderOrMethod::HeaderData(ref s) => (&**s).eq_ignore_ascii_case(header_name),
_ => false
}
}
fn match_method(&self, method: &Method) -> bool {
match *self {
HeaderOrMethod::MethodData(ref m) => m == method,
_ => false
}
}
}
/// An entry in the CORS cache
#[derive(Clone, Debug)]
pub struct CorsCacheEntry {
pub origin: Origin,
pub url: ServoUrl,
pub max_age: u32,
pub credentials: bool,
pub header_or_method: HeaderOrMethod,
created: Timespec
}
impl CorsCacheEntry {
fn new(origin: Origin, url: ServoUrl, max_age: u32, credentials: bool,
header_or_method: HeaderOrMethod) -> CorsCacheEntry {
CorsCacheEntry {
origin: origin,
url: url,
max_age: max_age,
credentials: credentials,
header_or_method: header_or_method,
created: time::now().to_timespec()
}
}
}
fn match_headers(cors_cache: &CorsCacheEntry, cors_req: &Request) -> bool {
cors_cache.origin == cors_req.origin &&
cors_cache.url == cors_req.current_url() &&
(cors_cache.credentials || cors_req.credentials_mode!= CredentialsMode::Include)
}
/// A simple, vector-based CORS Cache
#[derive(Clone)]
pub struct CorsCache(Vec<CorsCacheEntry>);
impl CorsCache {
pub fn new() -> CorsCache {
CorsCache(vec![])
}
fn find_entry_by_header<'a>(&'a mut self, request: &Request,
header_name: &str) -> Option<&'a mut CorsCacheEntry> {
self.cleanup();
self.0.iter_mut().find(|e| match_headers(e, request) && e.header_or_method.match_header(header_name))
}
fn find_entry_by_method<'a>(&'a mut self, request: &Request,
method: Method) -> Option<&'a mut CorsCacheEntry> {
// we can take the method from CorSRequest itself
self.cleanup();
self.0.iter_mut().find(|e| match_headers(e, request) && e.header_or_method.match_method(&method))
}
/// [Clear the cache](https://fetch.spec.whatwg.org/#concept-cache-clear)
pub fn clear(&mut self, request: &Request) {
let CorsCache(buf) = self.clone();
let new_buf: Vec<CorsCacheEntry> =
buf.into_iter().filter(|e| e.origin == request.origin &&
request.current_url() == e.url).collect();
*self = CorsCache(new_buf);
}
/// Remove old entries
pub fn cleanup(&mut self) {
let CorsCache(buf) = self.clone();
let now = time::now().to_timespec();
let new_buf: Vec<CorsCacheEntry> = buf.into_iter()
.filter(|e| now.sec < e.created.sec + e.max_age as i64)
.collect();
*self = CorsCache(new_buf);
}
/// Returns true if an entry with a
/// [matching header](https://fetch.spec.whatwg.org/#concept-cache-match-header) is found
pub fn match_header(&mut self, request: &Request, header_name: &str) -> bool {
self.find_entry_by_header(&request, header_name).is_some()
}
/// Updates max age if an entry for a
/// [matching header](https://fetch.spec.whatwg.org/#concept-cache-match-header) is found.
///
/// If not, it will insert an equivalent entry
pub fn match_header_and_update(&mut self, request: &Request,
header_name: &str, new_max_age: u32) -> bool {
match self.find_entry_by_header(&request, header_name).map(|e| e.max_age = new_max_age) {
Some(_) => true,
None => {
self.insert(CorsCacheEntry::new(request.origin.clone(), request.current_url(), new_max_age,
request.credentials_mode == CredentialsMode::Include,
HeaderOrMethod::HeaderData(header_name.to_owned())));
false
}
}
}
/// Returns true if an entry with a
/// [matching method](https://fetch.spec.whatwg.org/#concept-cache-match-method) is found
pub fn | (&mut self, request: &Request, method: Method) -> bool {
self.find_entry_by_method(&request, method).is_some()
}
/// Updates max age if an entry for
/// [a matching method](https://fetch.spec.whatwg.org/#concept-cache-match-method) is found.
///
/// If not, it will insert an equivalent entry
pub fn match_method_and_update(&mut self, request: &Request, method: Method, new_max_age: u32) -> bool {
match self.find_entry_by_method(&request, method.clone()).map(|e| e.max_age = new_max_age) {
Some(_) => true,
None => {
self.insert(CorsCacheEntry::new(request.origin.clone(), request.current_url(), new_max_age,
request.credentials_mode == CredentialsMode::Include,
HeaderOrMethod::MethodData(method)));
false
}
}
}
/// Insert an entry
pub fn insert(&mut self, entry: CorsCacheEntry) {
self.cleanup();
self.0.push(entry);
}
}
| match_method | identifier_name |
cors_cache.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/. */
//! An implementation of the [CORS preflight cache](https://fetch.spec.whatwg.org/#cors-preflight-cache)
//! For now this library is XHR-specific.
//! For stuff involving `<img>`, `<iframe>`, `<form>`, etc please check what
//! the request mode should be and compare with the fetch spec
//! This library will eventually become the core of the Fetch crate
//! with CORSRequest being expanded into FetchRequest (etc)
use hyper::method::Method;
use net_traits::request::{CredentialsMode, Origin, Request};
use servo_url::ServoUrl;
use std::ascii::AsciiExt;
use time::{self, Timespec};
/// Union type for CORS cache entries
///
/// Each entry might pertain to a header or method
#[derive(Clone, Debug)]
pub enum HeaderOrMethod {
HeaderData(String),
MethodData(Method)
}
impl HeaderOrMethod {
fn match_header(&self, header_name: &str) -> bool {
match *self {
HeaderOrMethod::HeaderData(ref s) => (&**s).eq_ignore_ascii_case(header_name),
_ => false
}
}
fn match_method(&self, method: &Method) -> bool {
match *self {
HeaderOrMethod::MethodData(ref m) => m == method,
_ => false
}
}
}
/// An entry in the CORS cache
#[derive(Clone, Debug)]
pub struct CorsCacheEntry {
pub origin: Origin,
pub url: ServoUrl, |
impl CorsCacheEntry {
fn new(origin: Origin, url: ServoUrl, max_age: u32, credentials: bool,
header_or_method: HeaderOrMethod) -> CorsCacheEntry {
CorsCacheEntry {
origin: origin,
url: url,
max_age: max_age,
credentials: credentials,
header_or_method: header_or_method,
created: time::now().to_timespec()
}
}
}
fn match_headers(cors_cache: &CorsCacheEntry, cors_req: &Request) -> bool {
cors_cache.origin == cors_req.origin &&
cors_cache.url == cors_req.current_url() &&
(cors_cache.credentials || cors_req.credentials_mode!= CredentialsMode::Include)
}
/// A simple, vector-based CORS Cache
#[derive(Clone)]
pub struct CorsCache(Vec<CorsCacheEntry>);
impl CorsCache {
pub fn new() -> CorsCache {
CorsCache(vec![])
}
fn find_entry_by_header<'a>(&'a mut self, request: &Request,
header_name: &str) -> Option<&'a mut CorsCacheEntry> {
self.cleanup();
self.0.iter_mut().find(|e| match_headers(e, request) && e.header_or_method.match_header(header_name))
}
fn find_entry_by_method<'a>(&'a mut self, request: &Request,
method: Method) -> Option<&'a mut CorsCacheEntry> {
// we can take the method from CorSRequest itself
self.cleanup();
self.0.iter_mut().find(|e| match_headers(e, request) && e.header_or_method.match_method(&method))
}
/// [Clear the cache](https://fetch.spec.whatwg.org/#concept-cache-clear)
pub fn clear(&mut self, request: &Request) {
let CorsCache(buf) = self.clone();
let new_buf: Vec<CorsCacheEntry> =
buf.into_iter().filter(|e| e.origin == request.origin &&
request.current_url() == e.url).collect();
*self = CorsCache(new_buf);
}
/// Remove old entries
pub fn cleanup(&mut self) {
let CorsCache(buf) = self.clone();
let now = time::now().to_timespec();
let new_buf: Vec<CorsCacheEntry> = buf.into_iter()
.filter(|e| now.sec < e.created.sec + e.max_age as i64)
.collect();
*self = CorsCache(new_buf);
}
/// Returns true if an entry with a
/// [matching header](https://fetch.spec.whatwg.org/#concept-cache-match-header) is found
pub fn match_header(&mut self, request: &Request, header_name: &str) -> bool {
self.find_entry_by_header(&request, header_name).is_some()
}
/// Updates max age if an entry for a
/// [matching header](https://fetch.spec.whatwg.org/#concept-cache-match-header) is found.
///
/// If not, it will insert an equivalent entry
pub fn match_header_and_update(&mut self, request: &Request,
header_name: &str, new_max_age: u32) -> bool {
match self.find_entry_by_header(&request, header_name).map(|e| e.max_age = new_max_age) {
Some(_) => true,
None => {
self.insert(CorsCacheEntry::new(request.origin.clone(), request.current_url(), new_max_age,
request.credentials_mode == CredentialsMode::Include,
HeaderOrMethod::HeaderData(header_name.to_owned())));
false
}
}
}
/// Returns true if an entry with a
/// [matching method](https://fetch.spec.whatwg.org/#concept-cache-match-method) is found
pub fn match_method(&mut self, request: &Request, method: Method) -> bool {
self.find_entry_by_method(&request, method).is_some()
}
/// Updates max age if an entry for
/// [a matching method](https://fetch.spec.whatwg.org/#concept-cache-match-method) is found.
///
/// If not, it will insert an equivalent entry
pub fn match_method_and_update(&mut self, request: &Request, method: Method, new_max_age: u32) -> bool {
match self.find_entry_by_method(&request, method.clone()).map(|e| e.max_age = new_max_age) {
Some(_) => true,
None => {
self.insert(CorsCacheEntry::new(request.origin.clone(), request.current_url(), new_max_age,
request.credentials_mode == CredentialsMode::Include,
HeaderOrMethod::MethodData(method)));
false
}
}
}
/// Insert an entry
pub fn insert(&mut self, entry: CorsCacheEntry) {
self.cleanup();
self.0.push(entry);
}
} | pub max_age: u32,
pub credentials: bool,
pub header_or_method: HeaderOrMethod,
created: Timespec
} | random_line_split |
cors_cache.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/. */
//! An implementation of the [CORS preflight cache](https://fetch.spec.whatwg.org/#cors-preflight-cache)
//! For now this library is XHR-specific.
//! For stuff involving `<img>`, `<iframe>`, `<form>`, etc please check what
//! the request mode should be and compare with the fetch spec
//! This library will eventually become the core of the Fetch crate
//! with CORSRequest being expanded into FetchRequest (etc)
use hyper::method::Method;
use net_traits::request::{CredentialsMode, Origin, Request};
use servo_url::ServoUrl;
use std::ascii::AsciiExt;
use time::{self, Timespec};
/// Union type for CORS cache entries
///
/// Each entry might pertain to a header or method
#[derive(Clone, Debug)]
pub enum HeaderOrMethod {
HeaderData(String),
MethodData(Method)
}
impl HeaderOrMethod {
fn match_header(&self, header_name: &str) -> bool {
match *self {
HeaderOrMethod::HeaderData(ref s) => (&**s).eq_ignore_ascii_case(header_name),
_ => false
}
}
fn match_method(&self, method: &Method) -> bool {
match *self {
HeaderOrMethod::MethodData(ref m) => m == method,
_ => false
}
}
}
/// An entry in the CORS cache
#[derive(Clone, Debug)]
pub struct CorsCacheEntry {
pub origin: Origin,
pub url: ServoUrl,
pub max_age: u32,
pub credentials: bool,
pub header_or_method: HeaderOrMethod,
created: Timespec
}
impl CorsCacheEntry {
fn new(origin: Origin, url: ServoUrl, max_age: u32, credentials: bool,
header_or_method: HeaderOrMethod) -> CorsCacheEntry {
CorsCacheEntry {
origin: origin,
url: url,
max_age: max_age,
credentials: credentials,
header_or_method: header_or_method,
created: time::now().to_timespec()
}
}
}
fn match_headers(cors_cache: &CorsCacheEntry, cors_req: &Request) -> bool |
/// A simple, vector-based CORS Cache
#[derive(Clone)]
pub struct CorsCache(Vec<CorsCacheEntry>);
impl CorsCache {
pub fn new() -> CorsCache {
CorsCache(vec![])
}
fn find_entry_by_header<'a>(&'a mut self, request: &Request,
header_name: &str) -> Option<&'a mut CorsCacheEntry> {
self.cleanup();
self.0.iter_mut().find(|e| match_headers(e, request) && e.header_or_method.match_header(header_name))
}
fn find_entry_by_method<'a>(&'a mut self, request: &Request,
method: Method) -> Option<&'a mut CorsCacheEntry> {
// we can take the method from CorSRequest itself
self.cleanup();
self.0.iter_mut().find(|e| match_headers(e, request) && e.header_or_method.match_method(&method))
}
/// [Clear the cache](https://fetch.spec.whatwg.org/#concept-cache-clear)
pub fn clear(&mut self, request: &Request) {
let CorsCache(buf) = self.clone();
let new_buf: Vec<CorsCacheEntry> =
buf.into_iter().filter(|e| e.origin == request.origin &&
request.current_url() == e.url).collect();
*self = CorsCache(new_buf);
}
/// Remove old entries
pub fn cleanup(&mut self) {
let CorsCache(buf) = self.clone();
let now = time::now().to_timespec();
let new_buf: Vec<CorsCacheEntry> = buf.into_iter()
.filter(|e| now.sec < e.created.sec + e.max_age as i64)
.collect();
*self = CorsCache(new_buf);
}
/// Returns true if an entry with a
/// [matching header](https://fetch.spec.whatwg.org/#concept-cache-match-header) is found
pub fn match_header(&mut self, request: &Request, header_name: &str) -> bool {
self.find_entry_by_header(&request, header_name).is_some()
}
/// Updates max age if an entry for a
/// [matching header](https://fetch.spec.whatwg.org/#concept-cache-match-header) is found.
///
/// If not, it will insert an equivalent entry
pub fn match_header_and_update(&mut self, request: &Request,
header_name: &str, new_max_age: u32) -> bool {
match self.find_entry_by_header(&request, header_name).map(|e| e.max_age = new_max_age) {
Some(_) => true,
None => {
self.insert(CorsCacheEntry::new(request.origin.clone(), request.current_url(), new_max_age,
request.credentials_mode == CredentialsMode::Include,
HeaderOrMethod::HeaderData(header_name.to_owned())));
false
}
}
}
/// Returns true if an entry with a
/// [matching method](https://fetch.spec.whatwg.org/#concept-cache-match-method) is found
pub fn match_method(&mut self, request: &Request, method: Method) -> bool {
self.find_entry_by_method(&request, method).is_some()
}
/// Updates max age if an entry for
/// [a matching method](https://fetch.spec.whatwg.org/#concept-cache-match-method) is found.
///
/// If not, it will insert an equivalent entry
pub fn match_method_and_update(&mut self, request: &Request, method: Method, new_max_age: u32) -> bool {
match self.find_entry_by_method(&request, method.clone()).map(|e| e.max_age = new_max_age) {
Some(_) => true,
None => {
self.insert(CorsCacheEntry::new(request.origin.clone(), request.current_url(), new_max_age,
request.credentials_mode == CredentialsMode::Include,
HeaderOrMethod::MethodData(method)));
false
}
}
}
/// Insert an entry
pub fn insert(&mut self, entry: CorsCacheEntry) {
self.cleanup();
self.0.push(entry);
}
}
| {
cors_cache.origin == cors_req.origin &&
cors_cache.url == cors_req.current_url() &&
(cors_cache.credentials || cors_req.credentials_mode != CredentialsMode::Include)
} | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.