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 |
|---|---|---|---|---|
issue-2935.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 ... | (&self) { }
}
pub fn main() {
// let x = ({a: 4i} as it);
// let y = @({a: 4i});
// let z = @({a: 4i} as it);
// let z = @({a: true} as it);
let z = @(@true as @it);
// x.f();
// y.f();
// (*z).f();
error!("ok so far...");
z.f(); //segfault
}
| f | identifier_name |
htmlappletelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public | * License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::attr::AttrValue;
use dom::bindings::codegen::Bindings::HTMLAppletElementBinding;
use dom::bindings::codegen::Bindings::HTMLAppletElementBinding::HTMLAppletElementMethods;
use d... | random_line_split | |
htmlappletelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::attr::AttrValue;
use dom::bindings::codegen::Bindings::HTMLAppletElementBinding;
use dom::bindings::codeg... |
}
impl HTMLAppletElementMethods for HTMLAppletElement {
// https://html.spec.whatwg.org/multipage/#the-applet-element:dom-applet-name
make_getter!(Name);
// https://html.spec.whatwg.org/multipage/#the-applet-element:dom-applet-name
make_atomic_setter!(SetName, "name");
}
impl VirtualMethods for HTML... | {
let element = HTMLAppletElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLAppletElementBinding::Wrap)
} | identifier_body |
htmlappletelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::attr::AttrValue;
use dom::bindings::codegen::Bindings::HTMLAppletElementBinding;
use dom::bindings::codeg... | (localName: DOMString,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLAppletElement> {
let element = HTMLAppletElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLAppletElementBinding::Wrap)
}
}
impl HTMLApple... | new | identifier_name |
regions-enum-not-wf.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 ... | // except according to those terms.
// Various examples of structs whose fields are not well-formed.
#![allow(dead_code)]
enum Ref1<'a, T> {
Ref1Variant1(&'a T) //~ ERROR the parameter type `T` may not live long enough
}
enum Ref2<'a, T> {
Ref2Variant1,
Ref2Variant2(isize, &'a T), //~ ERROR the paramete... | // option. This file may not be copied, modified, or distributed | random_line_split |
regions-enum-not-wf.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 ... | <'a, T> {
Ref1Variant1(&'a T) //~ ERROR the parameter type `T` may not live long enough
}
enum Ref2<'a, T> {
Ref2Variant1,
Ref2Variant2(isize, &'a T), //~ ERROR the parameter type `T` may not live long enough
}
enum RefOk<'a, T:'a> {
RefOkVariant1(&'a T)
}
enum RefIndirect<'a, T> {
RefIndirectVar... | Ref1 | identifier_name |
common.rs | //! The module contains some common utilities for `solicit::http` tests.
use std::io;
use std::rc::Rc;
use std::cell::{RefCell, Cell};
use std::borrow::Cow;
use std::io::{Cursor, Read, Write};
use http::{HttpResult, HttpScheme, StreamId, Header, OwnedHeader, ErrorCode};
use http::frame::{RawFrame, FrameIR, FrameHeade... | data: &[u8],
_: &mut HttpConnection)
-> HttpResult<()> {
if!self.silent {
assert_eq!(&self.chunks[self.curr_chunk], &data);
}
self.curr_chunk += 1;
Ok(())
}
fn new_headers<'n, 'v>(&mut self,
... | impl Session for TestSession {
fn new_data_chunk(&mut self,
_: StreamId, | random_line_split |
common.rs | //! The module contains some common utilities for `solicit::http` tests.
use std::io;
use std::rc::Rc;
use std::cell::{RefCell, Cell};
use std::borrow::Cow;
use std::io::{Cursor, Read, Write};
use http::{HttpResult, HttpScheme, StreamId, Header, OwnedHeader, ErrorCode};
use http::frame::{RawFrame, FrameIR, FrameHeade... |
fn on_rst_stream(&mut self, error: ErrorCode) {
self.errors.push(error);
self.close();
}
fn get_data_chunk(&mut self, buf: &mut [u8]) -> Result<StreamDataChunk, StreamDataError> {
if self.is_closed_local() {
return Err(StreamDataError::Closed);
}
let chu... | {
self.state = state;
} | identifier_body |
common.rs | //! The module contains some common utilities for `solicit::http` tests.
use std::io;
use std::rc::Rc;
use std::cell::{RefCell, Cell};
use std::borrow::Cow;
use std::io::{Cursor, Read, Write};
use http::{HttpResult, HttpScheme, StreamId, Header, OwnedHeader, ErrorCode};
use http::frame::{RawFrame, FrameIR, FrameHeade... | {
pub silent: bool,
/// List of expected headers -- in the order that they are expected
pub headers: Vec<Vec<OwnedHeader>>,
/// List of expected data chunks -- in the order that they are expected
pub chunks: Vec<Vec<u8>>,
/// The current number of header calls.
pub curr_header: usize,
/... | TestSession | identifier_name |
util.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.... | {
match s.starts_with("0x") {
true => s[2..].from_hex().unwrap(),
false => From::from(s)
}
} | identifier_body | |
util.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.... | (s: &str) -> Vec<u8> {
match s.starts_with("0x") {
true => s[2..].from_hex().unwrap(),
false => From::from(s)
}
}
| hex_or_string | identifier_name |
util.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or | // but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
use... | // (at your option) any later version.
// Parity is distributed in the hope that it will be useful, | random_line_split |
statvfs.rs | //! Get filesystem statistics
//!
//! See [the man pages](https://pubs.opengroup.org/onlinepubs/9699919799/functions/fstatvfs.html)
//! for more details.
use std::mem;
use std::os::unix::io::AsRawFd;
use libc::{self, c_ulong};
use crate::{Result, NixPath, errno::Errno};
#[cfg(not(target_os = "redox"))]
libc_bitflags... | ST_NODIRATIME;
/// Update access time relative to modify/change time
#[cfg(any(target_os = "android", all(target_os = "linux", not(target_env = "musl"))))]
ST_RELATIME;
}
);
/// Wrapper around the POSIX `statvfs` struct
///
/// For more information see the [`statvfs(3)` man pages](h... | #[cfg(any(target_os = "android", target_os = "linux"))] | random_line_split |
statvfs.rs | //! Get filesystem statistics
//!
//! See [the man pages](https://pubs.opengroup.org/onlinepubs/9699919799/functions/fstatvfs.html)
//! for more details.
use std::mem;
use std::os::unix::io::AsRawFd;
use libc::{self, c_ulong};
use crate::{Result, NixPath, errno::Errno};
#[cfg(not(target_os = "redox"))]
libc_bitflags... | (&self) -> libc::fsfilcnt_t {
self.0.f_favail
}
/// Get the file system id
pub fn filesystem_id(&self) -> c_ulong {
self.0.f_fsid
}
/// Get the mount flags
#[cfg(not(target_os = "redox"))]
pub fn flags(&self) -> FsFlags {
FsFlags::from_bits_truncate(self.0.f_flag)
... | files_available | identifier_name |
statvfs.rs | //! Get filesystem statistics
//!
//! See [the man pages](https://pubs.opengroup.org/onlinepubs/9699919799/functions/fstatvfs.html)
//! for more details.
use std::mem;
use std::os::unix::io::AsRawFd;
use libc::{self, c_ulong};
use crate::{Result, NixPath, errno::Errno};
#[cfg(not(target_os = "redox"))]
libc_bitflags... |
/// Get the number of free file inodes for unprivileged users
pub fn files_available(&self) -> libc::fsfilcnt_t {
self.0.f_favail
}
/// Get the file system id
pub fn filesystem_id(&self) -> c_ulong {
self.0.f_fsid
}
/// Get the mount flags
#[cfg(not(target_os = "redox... | {
self.0.f_ffree
} | identifier_body |
test_texture.rs | extern crate image;
use std::path::Path;
use self::image::GenericImage;
#[allow(unused_imports)]
use std::collections::HashMap;
#[allow(unused_imports)]
use implement::render::texture::{ TextureNormalized, TextureBuiltin, Texture, Channel };
#[allow(unused_imports)]
use implement::render::texture;
#[test]
pub fn te... | let t_modulated_checker : Texture = texture::modulate( &t_checker, &channel_val );
assert!( 255u8 == t_modulated_solid[(0usize,Channel::R)] );
assert!( 120u8 == t_modulated_solid[(0usize,Channel::G)] );
assert!( 0u8 == t_modulated_solid[(0usize,Channel::B)] );
assert!( 0u8 == t_modulated_checker[(... | {
//test for loading image into texture
let img = image::open( &Path::new( "core/asset/images/texture0.jpg" ) ).unwrap();
println!( "image dimension: {:?}", img.dimensions() );
println!( "image type: {:?}", img.color() );
// let texture0 = texture::Texture::from( &img );
//let texture_data = Ve... | identifier_body |
test_texture.rs | extern crate image;
use std::path::Path;
use self::image::GenericImage;
#[allow(unused_imports)]
use std::collections::HashMap;
#[allow(unused_imports)]
use implement::render::texture::{ TextureNormalized, TextureBuiltin, Texture, Channel };
#[allow(unused_imports)]
use implement::render::texture;
#[test]
pub fn te... | } | random_line_split | |
test_texture.rs | extern crate image;
use std::path::Path;
use self::image::GenericImage;
#[allow(unused_imports)]
use std::collections::HashMap;
#[allow(unused_imports)]
use implement::render::texture::{ TextureNormalized, TextureBuiltin, Texture, Channel };
#[allow(unused_imports)]
use implement::render::texture;
#[test]
pub fn | () {
//test for loading image into texture
let img = image::open( &Path::new( "core/asset/images/texture0.jpg" ) ).unwrap();
println!( "image dimension: {:?}", img.dimensions() );
println!( "image type: {:?}", img.color() );
// let texture0 = texture::Texture::from( &img );
//let texture_data =... | test_texture | identifier_name |
timeout.rs | use crate::stream_ext::Fuse;
use crate::Stream;
use tokio::time::{Instant, Sleep};
use core::future::Future;
use core::pin::Pin;
use core::task::{Context, Poll};
use pin_project_lite::pin_project;
use std::fmt;
use std::time::Duration;
pin_project! {
/// Stream returned by the [`timeout`](super::StreamExt::timeou... |
return Poll::Ready(v.map(Ok));
}
Poll::Pending => {}
};
if *me.poll_deadline {
ready!(me.deadline.poll(cx));
*me.poll_deadline = false;
return Poll::Ready(Some(Err(Elapsed::new())));
}
Poll::Pending
}
... | {
let next = Instant::now() + *me.duration;
me.deadline.reset(next);
*me.poll_deadline = true;
} | conditional_block |
timeout.rs | use crate::stream_ext::Fuse;
use crate::Stream;
use tokio::time::{Instant, Sleep};
use core::future::Future;
use core::pin::Pin;
use core::task::{Context, Poll};
use pin_project_lite::pin_project;
use std::fmt;
use std::time::Duration;
pin_project! {
/// Stream returned by the [`timeout`](super::StreamExt::timeou... |
Poll::Pending
}
fn size_hint(&self) -> (usize, Option<usize>) {
let (lower, upper) = self.stream.size_hint();
// The timeout stream may insert an error before and after each message
// from the underlying stream, but no more than one error between each
// message. Hen... | {
let me = self.project();
match me.stream.poll_next(cx) {
Poll::Ready(v) => {
if v.is_some() {
let next = Instant::now() + *me.duration;
me.deadline.reset(next);
*me.poll_deadline = true;
}
... | identifier_body |
timeout.rs | use crate::stream_ext::Fuse;
use crate::Stream;
use tokio::time::{Instant, Sleep};
use core::future::Future;
use core::pin::Pin;
use core::task::{Context, Poll};
use pin_project_lite::pin_project;
use std::fmt;
use std::time::Duration;
pin_project! {
/// Stream returned by the [`timeout`](super::StreamExt::timeou... | return Poll::Ready(v.map(Ok));
}
Poll::Pending => {}
};
if *me.poll_deadline {
ready!(me.deadline.poll(cx));
*me.poll_deadline = false;
return Poll::Ready(Some(Err(Elapsed::new())));
}
Poll::Pending
}
... | random_line_split | |
timeout.rs | use crate::stream_ext::Fuse;
use crate::Stream;
use tokio::time::{Instant, Sleep};
use core::future::Future;
use core::pin::Pin;
use core::task::{Context, Poll};
use pin_project_lite::pin_project;
use std::fmt;
use std::time::Duration;
pin_project! {
/// Stream returned by the [`timeout`](super::StreamExt::timeou... | (&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
"deadline has elapsed".fmt(fmt)
}
}
impl std::error::Error for Elapsed {}
impl From<Elapsed> for std::io::Error {
fn from(_err: Elapsed) -> std::io::Error {
std::io::ErrorKind::TimedOut.into()
}
}
| fmt | identifier_name |
lib.rs | //! # The Redox OS Kernel, version 2
//!
//! The Redox OS Kernel is a hybrid kernel that supports X86_64 systems and
//! provides Unix-like syscalls for primarily Rust applications
#![deny(warnings)]
#![feature(alloc)]
#![feature(asm)]
#![feature(collections)]
#![feature(const_fn)]
#![feature(core_intrinsics)]
#![feat... | unsafe {
interrupt::disable();
if context::switch() {
interrupt::enable_and_nop();
} else {
// Enable interrupts, then halt CPU (to save power) until the next interrupt is actually fired.
interrupt::enable_and_halt();
... | {
CPU_ID.store(0, Ordering::SeqCst);
CPU_COUNT.store(cpus, Ordering::SeqCst);
context::init();
let pid = syscall::getpid();
println!("BSP: {:?} {}", pid, cpus);
match context::contexts_mut().spawn(userspace_init) {
Ok(context_lock) => {
let mut context = context_lock.write... | identifier_body |
lib.rs | //! # The Redox OS Kernel, version 2
//!
//! The Redox OS Kernel is a hybrid kernel that supports X86_64 systems and
//! provides Unix-like syscalls for primarily Rust applications
#![deny(warnings)]
#![feature(alloc)]
#![feature(asm)]
#![feature(collections)]
#![feature(const_fn)]
#![feature(core_intrinsics)]
#![feat... |
}
syscall::exit(signal & 0x7F);
}
/// This is the kernel entry point for the primary CPU. The arch crate is responsible for calling this
#[no_mangle]
pub extern fn kmain(cpus: usize) {
CPU_ID.store(0, Ordering::SeqCst);
CPU_COUNT.store(cpus, Ordering::SeqCst);
context::init();
let pid = sysc... | {
let context = context_lock.read();
println!("NAME {}", unsafe { ::core::str::from_utf8_unchecked(&context.name.lock()) });
} | conditional_block |
lib.rs | //! # The Redox OS Kernel, version 2
//!
//! The Redox OS Kernel is a hybrid kernel that supports X86_64 systems and
//! provides Unix-like syscalls for primarily Rust applications
#![deny(warnings)]
#![feature(alloc)]
#![feature(asm)]
#![feature(collections)]
#![feature(const_fn)]
#![feature(core_intrinsics)]
#![feat... | interrupt::disable();
if context::switch() {
interrupt::enable_and_nop();
} else {
// Enable interrupts, then halt CPU (to save power) until the next interrupt is actually fired.
interrupt::enable_and_halt();
}
}
... | println!("AP {}: {:?}", id, pid);
loop {
unsafe { | random_line_split |
lib.rs | //! # The Redox OS Kernel, version 2
//!
//! The Redox OS Kernel is a hybrid kernel that supports X86_64 systems and
//! provides Unix-like syscalls for primarily Rust applications
#![deny(warnings)]
#![feature(alloc)]
#![feature(asm)]
#![feature(collections)]
#![feature(const_fn)]
#![feature(core_intrinsics)]
#![feat... | () {
assert_eq!(syscall::chdir(b"initfs:"), Ok(0));
assert_eq!(syscall::open(b"debug:", syscall::flag::O_RDONLY).map(FileHandle::into), Ok(0));
assert_eq!(syscall::open(b"debug:", syscall::flag::O_WRONLY).map(FileHandle::into), Ok(1));
assert_eq!(syscall::open(b"debug:", syscall::flag::O_WRONLY).map(Fi... | userspace_init | identifier_name |
lib.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/. */
#![feature(default_type_params, globs, macro_rules, phase, unsafe_destructor)]
#![deny(unsafe_blocks)]
#![deny(un... | extern crate hyper;
extern crate js;
extern crate libc;
extern crate msg;
extern crate net;
extern crate rustrt;
extern crate serialize;
extern crate time;
extern crate canvas;
extern crate script_traits;
#[phase(plugin)]
extern crate "plugins" as servo_plugins;
extern crate "net" as servo_net;
extern crate "util" as s... | extern crate encoding; | random_line_split |
kindck-impl-type-params.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 ... | <'a>() {
let t: Box<S<String>> = box S;
let a: Box<Gettable<String>> = t;
//~^ ERROR the trait `core::marker::Copy` is not implemented
}
fn main() { }
| foo3 | identifier_name |
kindck-impl-type-params.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 ... |
fn foo<'a>() {
let t: S<&'a int> = S;
let a = &t as &Gettable<&'a int>;
//~^ ERROR declared lifetime bound not satisfied
}
fn foo2<'a>() {
let t: Box<S<String>> = box S;
let a = t as Box<Gettable<String>>;
//~^ ERROR the trait `core::marker::Copy` is not implemented
}
fn foo3<'a>() {
let... | {
let t: S<T> = S;
let a: &Gettable<T> = &t;
//~^ ERROR the trait `core::marker::Send` is not implemented
//~^^ ERROR the trait `core::marker::Copy` is not implemented
} | identifier_body |
kindck-impl-type-params.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 ... | }
fn foo<'a>() {
let t: S<&'a int> = S;
let a = &t as &Gettable<&'a int>;
//~^ ERROR declared lifetime bound not satisfied
}
fn foo2<'a>() {
let t: Box<S<String>> = box S;
let a = t as Box<Gettable<String>>;
//~^ ERROR the trait `core::marker::Copy` is not implemented
}
fn foo3<'a>() {
le... | let a: &Gettable<T> = &t;
//~^ ERROR the trait `core::marker::Send` is not implemented
//~^^ ERROR the trait `core::marker::Copy` is not implemented | random_line_split |
bless.rs | //! `bless` updates the reference files in the repo with changed output files
//! from the last test run.
use std::ffi::OsStr;
use std::fs;
use std::lazy::SyncLazy;
use std::path::{Path, PathBuf};
use walkdir::WalkDir;
use crate::clippy_project_root;
static CLIPPY_BUILD_TIME: SyncLazy<Option<std::time::SystemTime>> ... |
// If the test output was not updated since the last clippy build, it may be outdated
if!ignore_timestamp &&!updated_since_clippy_build(&test_output_path).unwrap_or(true) {
return;
}
let test_output_file = fs::read(&test_output_path).expect("Unable to read test output file");
let referenc... | {
return;
} | conditional_block |
bless.rs | //! `bless` updates the reference files in the repo with changed output files
//! from the last test run.
use std::ffi::OsStr;
use std::fs;
use std::lazy::SyncLazy;
use std::path::{Path, PathBuf};
use walkdir::WalkDir;
use crate::clippy_project_root;
static CLIPPY_BUILD_TIME: SyncLazy<Option<std::time::SystemTime>> ... |
fn build_dir() -> PathBuf {
let mut path = std::env::current_exe().unwrap();
path.set_file_name("test");
path
}
| {
let clippy_build_time = (*CLIPPY_BUILD_TIME)?;
let modified = fs::metadata(path).ok()?.modified().ok()?;
Some(modified >= clippy_build_time)
} | identifier_body |
bless.rs | //! `bless` updates the reference files in the repo with changed output files
//! from the last test run.
use std::ffi::OsStr;
use std::fs;
use std::lazy::SyncLazy;
use std::path::{Path, PathBuf};
use walkdir::WalkDir;
use crate::clippy_project_root;
static CLIPPY_BUILD_TIME: SyncLazy<Option<std::time::SystemTime>> ... | // We need to re-read the file now because it was potentially updated from copying
let reference_file = fs::read(&reference_file_path).unwrap_or_default();
if reference_file.is_empty() {
// If we copied over an empty output file, we remove the now empty reference file
pr... | println!("updating {}", &relative_reference_file_path.display());
fs::copy(test_output_path, &reference_file_path).expect("Could not update reference file");
| random_line_split |
bless.rs | //! `bless` updates the reference files in the repo with changed output files
//! from the last test run.
use std::ffi::OsStr;
use std::fs;
use std::lazy::SyncLazy;
use std::path::{Path, PathBuf};
use walkdir::WalkDir;
use crate::clippy_project_root;
static CLIPPY_BUILD_TIME: SyncLazy<Option<std::time::SystemTime>> ... | (ignore_timestamp: bool) {
let test_suite_dirs = [
clippy_project_root().join("tests").join("ui"),
clippy_project_root().join("tests").join("ui-internal"),
clippy_project_root().join("tests").join("ui-toml"),
clippy_project_root().join("tests").join("ui-cargo"),
];
for test_s... | bless | identifier_name |
test.rs | use rand::{SeedableRng, Rng, rngs::SmallRng};
// Having more than 1 test does seem to make a difference
// (i.e., this calls ptr::swap which having just one test does not).
#[test]
fn simple1() |
#[test]
fn simple2() {
assert_ne!(42, 24);
}
// A test that won't work on miri (tests disabling tests).
#[test]
#[cfg_attr(miri, ignore)]
fn does_not_work_on_miri() {
let x = 0u8;
assert!(&x as *const _ as usize % 4 < 4);
}
// We also use this to test some external crates, that we cannot depend on in th... | {
assert_eq!(4, 4);
} | identifier_body |
test.rs | use rand::{SeedableRng, Rng, rngs::SmallRng};
// Having more than 1 test does seem to make a difference
// (i.e., this calls ptr::swap which having just one test does not).
#[test]
fn simple1() {
assert_eq!(4, 4);
}
#[test]
fn simple2() {
assert_ne!(42, 24);
}
// A test that won't work on miri (tests disabli... | () {
assert_eq!(num_cpus::get(), 1);
}
// FIXME: Remove this `cfg` once we fix https://github.com/rust-lang/miri/issues/1059.
// We cfg-gate the `should_panic` attribute and the `panic!` itself, so that the test
// stdout does not depend on the platform.
#[test]
#[cfg_attr(not(windows), should_panic(expected="Exp... | num_cpus | identifier_name |
test.rs | use rand::{SeedableRng, Rng, rngs::SmallRng};
// Having more than 1 test does seem to make a difference
// (i.e., this calls ptr::swap which having just one test does not).
#[test]
fn simple1() {
assert_eq!(4, 4);
}
#[test]
fn simple2() {
assert_ne!(42, 24);
}
// A test that won't work on miri (tests disabli... | // We cfg-gate the `should_panic` attribute and the `panic!` itself, so that the test
// stdout does not depend on the platform.
#[test]
#[cfg_attr(not(windows), should_panic(expected="Explicit panic"))]
fn do_panic() { // In large, friendly letters :)
#[cfg(not(windows))]
panic!("Explicit panic from test!");
}... | }
// FIXME: Remove this `cfg` once we fix https://github.com/rust-lang/miri/issues/1059. | random_line_split |
config.rs | //! Configuration module, read and write config file.
use APP_INFO;
use error::*;
use json::JsonValue;
use std::fs::File;
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
use vars::VarsHandler;
/// Configuration structure to read and write config.
#[derive(Clone, Debug)]
pub struct Config {
/// Path to... | () -> Config {
let metadata_path = ::app_dirs::app_root(::app_dirs::AppDataType::UserData, &APP_INFO)
.unwrap()
.join("metadata.json");
let vars_path = VarsHandler::get_default_path().unwrap();
Config::new(metadata_path, 3600, vars_path)
}
}
#[cfg(test)]
mod unit_tests... | default | identifier_name |
config.rs | //! Configuration module, read and write config file.
use APP_INFO;
use error::*;
use json::JsonValue;
use std::fs::File;
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
use vars::VarsHandler;
/// Configuration structure to read and write config.
#[derive(Clone, Debug)]
pub struct Config {
/// Path to... |
/// Read config from readable stream
pub fn from_json_stream<R: Read>(stream: &mut R) -> Result<Config> {
let mut buf = String::new();
stream.read_to_string(&mut buf)?;
let json = ::json::parse(&buf)?;
let metadata_path = match json["metadata_path"].as_str() {
Some(s... | ::app_dirs::app_root(::app_dirs::AppDataType::UserConfig, &APP_INFO)?
.join("config"),
)
} | random_line_split |
config.rs | //! Configuration module, read and write config file.
use APP_INFO;
use error::*;
use json::JsonValue;
use std::fs::File;
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
use vars::VarsHandler;
/// Configuration structure to read and write config.
#[derive(Clone, Debug)]
pub struct Config {
/// Path to... |
/// Path to the config
pub fn config_path() -> Result<PathBuf> {
Ok(
::app_dirs::app_root(::app_dirs::AppDataType::UserConfig, &APP_INFO)?
.join("config"),
)
}
/// Read config from readable stream
pub fn from_json_stream<R: Read>(stream: &mut R) -> Resul... | {
Config {
metadata_path: metadata_path.as_ref().to_path_buf(),
autobackup_interval: autobackup_interval,
vars_path: vars_path.as_ref().to_path_buf(),
}
} | identifier_body |
sqlreturn.rs | /// Indicates the overall success or failure of the function
///
/// Each function in ODBC returns a code, known as its return code, which indicates the overall
/// success or failure of the function. Program logic is generally based on return codes.
/// See [ODBC reference](https://docs.microsoft.com/en-us/sql/odbc/re... | ///
/// The application calls `SQLGetDiagRec` or `SQLGetDiagField` to retrieve additional
/// information.
pub const SUCCESS_WITH_INFO: SqlReturn = SqlReturn(1);
/// A function that was started asynchronously is still executing
///
/// The application `SQLGetDiagRec` or `SQLGetDiagField` to... | /// record.
pub const SUCCESS: SqlReturn = SqlReturn(0);
/// Function completed successfully, possibly with a nonfatal error (warning) | random_line_split |
sqlreturn.rs | /// Indicates the overall success or failure of the function
///
/// Each function in ODBC returns a code, known as its return code, which indicates the overall
/// success or failure of the function. Program logic is generally based on return codes.
/// See [ODBC reference](https://docs.microsoft.com/en-us/sql/odbc/re... | (pub i16);
impl SqlReturn {
/// `SQL_INVALID_HANDLE`; Function failed due to an invalid environment, connection, statement,
/// or descriptor handle.
///
/// This indicates a programming error. No additional information is available from
/// `SQLGetDiagRec` or `SQLGetDiagField`. This code is return... | SqlReturn | identifier_name |
server.rs | use iron::prelude::*;
use iron::status;
use router::Router;
use urlencoded::UrlEncodedQuery;
fn handler(req: &mut Request) -> IronResult<Response> {
// match req.get_ref::<UrlEncodedQuery>() {
// Err(ref e) => {
// let err_msg = format!("{:?}", e); | // Ok(Response::with((status::Ok, "he")))
// }
// }
panic!("fix me, something in Iron broke")
}
pub fn run() {
let mut router = Router::new(); // Alternative syntax:
router.get("/check", handler); // get "/:query" => handler);
Iron::new(router).http("127.... | // Ok(Response::with((status::Ok, &err_msg[..])))
// },
// Ok(ref hashmap) => {
// println!("Parsed GET request query string:\n {:?}", hashmap); | random_line_split |
server.rs | use iron::prelude::*;
use iron::status;
use router::Router;
use urlencoded::UrlEncodedQuery;
fn handler(req: &mut Request) -> IronResult<Response> {
// match req.get_ref::<UrlEncodedQuery>() {
// Err(ref e) => {
// let err_msg = format!("{:?}", e);
// Ok(Response::with((status::Ok, ... | {
let mut router = Router::new(); // Alternative syntax:
router.get("/check", handler); // get "/:query" => handler);
Iron::new(router).http("127.0.0.1:3000").unwrap();
} | identifier_body | |
server.rs | use iron::prelude::*;
use iron::status;
use router::Router;
use urlencoded::UrlEncodedQuery;
fn | (req: &mut Request) -> IronResult<Response> {
// match req.get_ref::<UrlEncodedQuery>() {
// Err(ref e) => {
// let err_msg = format!("{:?}", e);
// Ok(Response::with((status::Ok, &err_msg[..])))
// },
// Ok(ref hashmap) => {
// println!("Parsed GET reques... | handler | identifier_name |
io_handler.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.... | (&self, io: &IoContext<ClientIoMessage>) {
io.register_timer(INFO_TIMER, 5000).expect("Error registering timer");
}
fn timeout(&self, _io: &IoContext<ClientIoMessage>, timer: TimerToken) {
if timer == INFO_TIMER &&!self.shutdown.load(Ordering::SeqCst) {
self.info.tick();
}
}
}
pub struct ImportIoHandler {... | initialize | identifier_name |
io_handler.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.... | pub shutdown: Arc<AtomicBool>
}
impl IoHandler<ClientIoMessage> for ClientIoHandler {
fn initialize(&self, io: &IoContext<ClientIoMessage>) {
io.register_timer(INFO_TIMER, 5000).expect("Error registering timer");
}
fn timeout(&self, _io: &IoContext<ClientIoMessage>, timer: TimerToken) {
if timer == INFO_TIMER... | pub accounts: Arc<AccountProvider>,
pub info: Arc<Informant>, | random_line_split |
io_handler.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.... |
}
}
pub struct ImportIoHandler {
pub info: Arc<Informant>,
}
impl IoHandler<ClientIoMessage> for ImportIoHandler {
fn initialize(&self, io: &IoContext<ClientIoMessage>) {
io.register_timer(INFO_TIMER, 5000).expect("Error registering timer");
}
fn timeout(&self, _io: &IoContext<ClientIoMessage>, timer: TimerT... | {
self.info.tick();
} | conditional_block |
mod.rs | // Copyright 2019 The Exonum Team
//
// 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 i... | <T: Access> {
pub counter: ProofEntry<T::Base, u64>,
}
impl<T: Access> CounterSchema<T> {
fn new(access: T) -> Self {
Self::from_root(access).unwrap()
}
}
impl<T> CounterSchema<T>
where
T: Access,
T::Base: RawAccessMut,
{
fn inc_counter(&mut self, inc: u64) -> u64 {
let count =... | CounterSchema | identifier_name |
mod.rs | // Copyright 2019 The Exonum Team
//
// 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 i... | fn before_transactions(&self, context: ExecutionContext<'_>) -> Result<(), ExecutionError> {
let mut schema = CounterSchema::new(context.service_data());
if schema.counter.get() == Some(13) {
schema.counter.set(0);
Err(Error::BadLuck.into())
} else {
Ok(()... | }
impl Service for CounterService { | random_line_split |
mod.rs | // Copyright 2019 The Exonum Team
//
// 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 i... |
}
fn after_transactions(&self, context: ExecutionContext<'_>) -> Result<(), ExecutionError> {
let schema = CounterSchema::new(context.service_data());
if schema.counter.get() == Some(42) {
Err(Error::AnswerToTheUltimateQuestion.into())
} else {
Ok(())
}
... | {
Ok(())
} | conditional_block |
support.rs | #![allow(dead_code)]
extern crate file_lock;
use std::env;
use std::borrow::Borrow;
use std::path::{PathBuf, Path};
use std::os::unix::io::{RawFd, AsRawFd};
use std::fs::{File, OpenOptions, remove_file};
use file_lock::fd::Mode;
/// A utility type to assure the removal of a file.
///
/// It is useful when a temporar... | <P: Borrow<PathBuf>> {
inner: File,
remover: Remover<P>
}
impl<P> TempFile<P> where P: Borrow<PathBuf> {
pub fn fd(&self) -> RawFd {
self.inner.as_raw_fd()
}
pub fn path(&self) -> &Path {
self.remover.path.borrow()
}
pub fn path_buf(&self) -> PathBuf {
self.remove... | TempFile | identifier_name |
support.rs | #![allow(dead_code)]
extern crate file_lock;
use std::env;
use std::borrow::Borrow;
use std::path::{PathBuf, Path};
use std::os::unix::io::{RawFd, AsRawFd};
use std::fs::{File, OpenOptions, remove_file};
use file_lock::fd::Mode;
/// A utility type to assure the removal of a file.
/// | /// It is useful when a temporary lock file is created. When an instance dropped
/// of this type is dropped, the lock file will be removed. It is not an error
/// if the file doesn't exist anymore.
///
pub struct Remover<P: Borrow<PathBuf>> {
pub path: P,
}
impl<P> Drop for Remover<P>
where P: Borrow<PathBuf> ... | random_line_split | |
support.rs | #![allow(dead_code)]
extern crate file_lock;
use std::env;
use std::borrow::Borrow;
use std::path::{PathBuf, Path};
use std::os::unix::io::{RawFd, AsRawFd};
use std::fs::{File, OpenOptions, remove_file};
use file_lock::fd::Mode;
/// A utility type to assure the removal of a file.
///
/// It is useful when a temporar... |
}
impl TempFile<PathBuf> {
pub fn new(name: &str, mode: Mode) -> TempFile<PathBuf> {
let mut path = env::temp_dir();
path.push(name);
TempFile {
inner: OpenOptions::new()
.create(true)
.read(mode == Mode::Read)
... | {
&mut self.inner
} | identifier_body |
lib.rs | //! # Teleborg
//!
//! Teleborg is a fast, reliable and easy to use wrapper for the [Telegram bot
//! API](https://core.telegram.org/bots/api).
//! This crate aims to provide everything the user needs to create a high
//! performant Telegram bot.
//!
//! ## Getting started
//!
//! ``` no_run
//! extern crate teleborg;
... | (&mut self, bot: &Bot, update: objects::Update, args: Option<Vec<&str>>) {
self(bot, update, args);
}
}
/// Construct an API URL with the base bot URL and an
/// array of strings which will construct the path.
fn construct_api_url(bot_url: &str, path: &[&str]) -> String {
format!("{}/{}", bot_url, path... | execute | identifier_name |
lib.rs | //! # Teleborg
//!
//! Teleborg is a fast, reliable and easy to use wrapper for the [Telegram bot
//! API](https://core.telegram.org/bots/api).
//! This crate aims to provide everything the user needs to create a high
//! performant Telegram bot.
//!
//! ## Getting started
//!
//! ``` no_run
//! extern crate teleborg;
... | mod dispatcher;
mod marker;
mod updater;
/// Pass this to a method which requires markup where you do not want markup.
pub const NO_MARKUP: Option<objects::NullMarkup> = None;
impl<T: Sync + Send +'static + FnMut(&Bot, objects::Update, Option<Vec<&str>>)> Command for T {
fn execute(&mut self, bot: &Bot, update: o... | mod bot;
mod command; | random_line_split |
lib.rs | //! # Teleborg
//!
//! Teleborg is a fast, reliable and easy to use wrapper for the [Telegram bot
//! API](https://core.telegram.org/bots/api).
//! This crate aims to provide everything the user needs to create a high
//! performant Telegram bot.
//!
//! ## Getting started
//!
//! ``` no_run
//! extern crate teleborg;
... |
}
/// Construct an API URL with the base bot URL and an
/// array of strings which will construct the path.
fn construct_api_url(bot_url: &str, path: &[&str]) -> String {
format!("{}/{}", bot_url, path.join("/"))
}
| {
self(bot, update, args);
} | identifier_body |
coherence-overlap-all-t-and-tuple.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 ... |
}
impl <T> From<T> for T {
}
impl <T11, U11> From<(U11,)> for (T11,) { //~ ERROR E0119
}
fn main() { }
| {} | identifier_body |
coherence-overlap-all-t-and-tuple.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 ... | () {}
}
impl <T> From<T> for T {
}
impl <T11, U11> From<(U11,)> for (T11,) { //~ ERROR E0119
}
fn main() { }
| foo | identifier_name |
coherence-overlap-all-t-and-tuple.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 ... | // Check that we detect an overlap here in the case where:
//
// for some type X:
// T = (X,)
// T11 = X, U11 = X
//
// Seems pretty basic, but then there was issue #24241. :)
trait From<U> {
fn foo() {}
}
impl <T> From<T> for T {
}
impl <T11, U11> From<(U11,)> for (T11,) { //~ ERROR E0119
}
fn mai... | random_line_split | |
extendableevent.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::EventBinding::EventMethods;
use dom::bindings::codegen::Bindings::Extendable... | (global: GlobalRef,
type_: Atom,
bubbles: bool,
cancelable: bool)
-> Root<ExtendableEvent> {
let ev = reflect_dom_object(box ExtendableEvent::new_inherited(), global, ExtendableEventBinding::Wrap);
{
let event = ev.upcast::<Event>()... | new | identifier_name |
extendableevent.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::EventBinding::EventMethods;
use dom::bindings::codegen::Bindings::Extendable... | }
// https://dom.spec.whatwg.org/#dom-event-istrusted
pub fn IsTrusted(&self) -> bool {
self.event.IsTrusted()
}
} | return Err(Error::InvalidState);
}
// Step 2
// TODO add a extended_promises array to enqueue the `val`
Ok(()) | random_line_split |
extendableevent.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::EventBinding::EventMethods;
use dom::bindings::codegen::Bindings::Extendable... |
// Step 2
// TODO add a extended_promises array to enqueue the `val`
Ok(())
}
// https://dom.spec.whatwg.org/#dom-event-istrusted
pub fn IsTrusted(&self) -> bool {
self.event.IsTrusted()
}
}
| {
return Err(Error::InvalidState);
} | conditional_block |
extendableevent.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::EventBinding::EventMethods;
use dom::bindings::codegen::Bindings::Extendable... |
pub fn new(global: GlobalRef,
type_: Atom,
bubbles: bool,
cancelable: bool)
-> Root<ExtendableEvent> {
let ev = reflect_dom_object(box ExtendableEvent::new_inherited(), global, ExtendableEventBinding::Wrap);
{
let event = ev.up... | {
ExtendableEvent {
event: Event::new_inherited(),
extensions_allowed: true
}
} | identifier_body |
in_process_lease.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use anyhow::Result;
use async_trait::async_trait;
use context::CoreContext;
use futures::{
channel::oneshot::{channel, Receiver, Sender... |
}
#[async_trait]
impl LeaseOps for InProcessLease {
async fn try_add_put_lease(&self, key: &str) -> Result<bool> {
let key = key.to_string();
let mut in_flight_leases = self.leases.lock().await;
let entry = in_flight_leases.entry(key);
if let Entry::Occupied(_) = entry {
... | {
Self {
leases: Arc::new(Mutex::new(HashMap::new())),
}
} | identifier_body |
in_process_lease.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use anyhow::Result;
use async_trait::async_trait;
use context::CoreContext;
use futures::{
channel::oneshot::{channel, Receiver, Sender... | async fn try_add_put_lease(&self, key: &str) -> Result<bool> {
let key = key.to_string();
let mut in_flight_leases = self.leases.lock().await;
let entry = in_flight_leases.entry(key);
if let Entry::Occupied(_) = entry {
Ok(false)
} else {
let (send, r... | random_line_split | |
in_process_lease.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use anyhow::Result;
use async_trait::async_trait;
use context::CoreContext;
use futures::{
channel::oneshot::{channel, Receiver, Sender... |
}
fn renew_lease_until(&self, _ctx: CoreContext, key: &str, done: BoxFuture<'static, ()>) {
let this = self.clone();
let key = key.to_string();
tokio::spawn(async move {
done.await;
this.release_lease(&key).await;
});
}
async fn wait_for_other_l... | {
let (send, recv) = channel();
entry.or_insert((send, recv.shared()));
Ok(true)
} | conditional_block |
in_process_lease.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use anyhow::Result;
use async_trait::async_trait;
use context::CoreContext;
use futures::{
channel::oneshot::{channel, Receiver, Sender... | () -> Self {
Self {
leases: Arc::new(Mutex::new(HashMap::new())),
}
}
}
#[async_trait]
impl LeaseOps for InProcessLease {
async fn try_add_put_lease(&self, key: &str) -> Result<bool> {
let key = key.to_string();
let mut in_flight_leases = self.leases.lock().await;
... | new | identifier_name |
context.rs | use ::handle::Handle;
/// A libudev context. Contexts may not be sent or shared between threads. The `libudev(3)` manpage
/// says:
///
/// > All functions require a libudev context to operate. This context can be create via
/// > udev_new(3). It is used to track library state and link objects together. No global stat... | }
} | /// Creates a new context.
pub fn new() -> ::Result<Self> {
Ok(Context {
udev: try_alloc!(unsafe { ::ffi::udev_new() }),
}) | random_line_split |
context.rs | use ::handle::Handle;
/// A libudev context. Contexts may not be sent or shared between threads. The `libudev(3)` manpage
/// says:
///
/// > All functions require a libudev context to operate. This context can be create via
/// > udev_new(3). It is used to track library state and link objects together. No global stat... | (&self) -> Self {
Context {
udev: unsafe { ::ffi::udev_ref(self.udev) },
}
}
}
impl Drop for Context {
/// Decrements reference count of `libudev` context.
fn drop(&mut self) {
unsafe {
::ffi::udev_unref(self.udev);
}
}
}
#[doc(hidden)]
impl Hand... | clone | identifier_name |
lib.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/. */
//! This module contains traits in script used generically in the rest of Servo.
//! The traits are here instead o... | {
Element,
HTMLCanvasElement,
HTMLIFrameElement,
HTMLImageElement,
HTMLInputElement,
HTMLObjectElement,
HTMLTableCellElement,
HTMLTableColElement,
HTMLTableElement,
HTMLTableRowElement,
HTMLTableSectionElement,
HTMLTextAreaElement,
SVGSVGElement,
}
pub struct HTMLCa... | LayoutElementType | identifier_name |
lib.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 |
//! This module contains traits in script used generically in the rest of Servo.
//! The traits are here instead of in script so that these modules won't have
//! to depend on script.
#![deny(unsafe_code)]
#![feature(box_syntax)]
#![feature(nonzero)]
extern crate app_units;
extern crate atomic_refcell;
extern crate ... | * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ | random_line_split |
complete.rs | use std::path::PathBuf;
pub trait Completer {
fn completions(&self, start: &str) -> Vec<String>;
}
pub struct BasicCompleter {
prefixes: Vec<String>,
}
impl BasicCompleter {
pub fn new<T: Into<String>>(prefixes: Vec<T>) -> BasicCompleter {
BasicCompleter { prefixes: prefixes.into_iter().map(|s| s... | fn completions(&self, mut start: &str) -> Vec<String> {
// XXX: this function is really bad, TODO rewrite
let start_owned;
if start.starts_with("\"") || start.starts_with("'") {
start = &start[1..];
if start.len() >= 1 {
start = &start[..start.len() -... | }
}
impl Completer for FilenameCompleter { | random_line_split |
complete.rs | use std::path::PathBuf;
pub trait Completer {
fn completions(&self, start: &str) -> Vec<String>;
}
pub struct BasicCompleter {
prefixes: Vec<String>,
}
impl BasicCompleter {
pub fn new<T: Into<String>>(prefixes: Vec<T>) -> BasicCompleter {
BasicCompleter { prefixes: prefixes.into_iter().map(|s| s... | (&self, mut start: &str) -> Vec<String> {
// XXX: this function is really bad, TODO rewrite
let start_owned;
if start.starts_with("\"") || start.starts_with("'") {
start = &start[1..];
if start.len() >= 1 {
start = &start[..start.len() - 1];
}... | completions | identifier_name |
complete.rs | use std::path::PathBuf;
pub trait Completer {
fn completions(&self, start: &str) -> Vec<String>;
}
pub struct BasicCompleter {
prefixes: Vec<String>,
}
impl BasicCompleter {
pub fn new<T: Into<String>>(prefixes: Vec<T>) -> BasicCompleter {
BasicCompleter { prefixes: prefixes.into_iter().map(|s| s... |
}
pub struct FilenameCompleter {
working_dir: Option<PathBuf>,
}
impl FilenameCompleter {
pub fn new<T: Into<PathBuf>>(working_dir: Option<T>) -> Self {
FilenameCompleter { working_dir: working_dir.map(|p| p.into()) }
}
}
impl Completer for FilenameCompleter {
fn completions(&self, mut start... | {
self.prefixes
.iter()
.filter(|s| s.starts_with(start))
.cloned()
.collect()
} | identifier_body |
irc_responder.rs | use command_with_sender_iter::CommandWithSenderIterable;
use star_handler::StarHandler;
use irc::client::prelude::*;
use std::sync::Arc;
pub struct IrcResponder {
starboard: StarHandler,
server : Arc<IrcServer>,
}
impl IrcResponder {
pub fn from_config(config: Config) -> IrcResponder |
pub fn handle(&mut self) {
for message in self.server.iter_cmd_sender() {
match message {
Ok((Command::JOIN(_, _, _), Some(sender))) =>
if sender == "StarBot" {
println!("I'm in")
},
Ok((Command::PRIVMSG(target, msg), sender)) => {
match (&target[..], &msg[..], sender.as_ref().map(|... | {
let server = Arc::new(IrcServer::from_config(config).unwrap());
server.identify().unwrap();
IrcResponder{
starboard: StarHandler::new(&server),
server : server,
}
} | identifier_body |
irc_responder.rs | use command_with_sender_iter::CommandWithSenderIterable;
use star_handler::StarHandler;
use irc::client::prelude::*;
use std::sync::Arc;
pub struct IrcResponder {
starboard: StarHandler,
server : Arc<IrcServer>,
}
impl IrcResponder {
pub fn from_config(config: Config) -> IrcResponder {
let server = Arc::new(I... | }
}
}
fn quit(&self) {
self.server.send_quit("Mára mesta").unwrap();
}
fn help(&self, whom: &str, level: i32) {
self.server.send_notice(whom, r#"Cummands, level 0:"#).unwrap();
self.server.send_notice(whom, r#" "add <" username ">" message content -- add your star to a message"#).unwrap();
self.serv... | random_line_split | |
irc_responder.rs | use command_with_sender_iter::CommandWithSenderIterable;
use star_handler::StarHandler;
use irc::client::prelude::*;
use std::sync::Arc;
pub struct IrcResponder {
starboard: StarHandler,
server : Arc<IrcServer>,
}
impl IrcResponder {
pub fn | (config: Config) -> IrcResponder {
let server = Arc::new(IrcServer::from_config(config).unwrap());
server.identify().unwrap();
IrcResponder{
starboard: StarHandler::new(&server),
server : server,
}
}
pub fn handle(&mut self) {
for message in self.server.iter_cmd_sender() {
match message {
O... | from_config | identifier_name |
size_of.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 script::test::size_of;
// Macro so that we can stringify type names
// I'd really prefer the tests themselves... | );
// Update the sizes here
sizeof_checker!(size_event_target, EventTarget, 40);
sizeof_checker!(size_node, Node, 184);
sizeof_checker!(size_element, Element, 352);
sizeof_checker!(size_htmlelement, HTMLElement, 368);
sizeof_checker!(size_div, HTMLDivElement, 368);
sizeof_checker!(size_span, HTMLSpanElement, 368);
siz... | avoids this increase. If you feel that the increase is necessary, \
update to the new size in tests/unit/script/size_of.rs.",
stringify!($t), old, new)
}
}); | random_line_split |
message_builder.rs | use session::{Session, ReceiptRequest, OutstandingReceipt};
use frame::Frame;
use option_setter::OptionSetter;
pub struct MessageBuilder<'a> {
pub session: &'a mut Session,
pub frame: Frame,
pub receipt_request: Option<ReceiptRequest>
}
impl<'a> MessageBuilder<'a> {
pub fn new(session: &'a mut Session... | <T>(self, option_setter: T) -> MessageBuilder<'a>
where T: OptionSetter<MessageBuilder<'a>>
{
option_setter.set_option(self)
}
}
| with | identifier_name |
message_builder.rs | use session::{Session, ReceiptRequest, OutstandingReceipt};
use frame::Frame;
use option_setter::OptionSetter;
pub struct MessageBuilder<'a> {
pub session: &'a mut Session,
pub frame: Frame,
pub receipt_request: Option<ReceiptRequest>
}
impl<'a> MessageBuilder<'a> {
pub fn new(session: &'a mut Session... |
self.session.send_frame(self.frame)
}
#[allow(dead_code)]
pub fn with<T>(self, option_setter: T) -> MessageBuilder<'a>
where T: OptionSetter<MessageBuilder<'a>>
{
option_setter.set_option(self)
}
}
| {
let request = self.receipt_request.unwrap();
self.session.state.outstanding_receipts.insert(
request.id,
OutstandingReceipt::new(
self.frame.clone()
)
);
} | conditional_block |
message_builder.rs | use session::{Session, ReceiptRequest, OutstandingReceipt};
use frame::Frame;
use option_setter::OptionSetter;
pub struct MessageBuilder<'a> {
pub session: &'a mut Session,
pub frame: Frame,
pub receipt_request: Option<ReceiptRequest>
}
impl<'a> MessageBuilder<'a> {
pub fn new(session: &'a mut Session... |
#[allow(dead_code)]
pub fn send(self) {
if self.receipt_request.is_some() {
let request = self.receipt_request.unwrap();
self.session.state.outstanding_receipts.insert(
request.id,
OutstandingReceipt::new(
self.frame.clone()
... | {
MessageBuilder {
session: session,
frame: frame,
receipt_request: None
}
} | identifier_body |
message_builder.rs | use session::{Session, ReceiptRequest, OutstandingReceipt};
use frame::Frame;
use option_setter::OptionSetter;
pub struct MessageBuilder<'a> {
pub session: &'a mut Session,
pub frame: Frame,
pub receipt_request: Option<ReceiptRequest>
}
impl<'a> MessageBuilder<'a> {
pub fn new(session: &'a mut Session... | where T: OptionSetter<MessageBuilder<'a>>
{
option_setter.set_option(self)
}
} |
#[allow(dead_code)]
pub fn with<T>(self, option_setter: T) -> MessageBuilder<'a> | random_line_split |
cursor.rs | //! Cursor movement.
use std::fmt;
use std::ops;
use std::io::{self, Write, Error, ErrorKind, Read};
use async::async_stdin_until;
use std::time::{SystemTime, Duration};
use raw::CONTROL_SEQUENCE_TIMEOUT;
use numtoa::NumToA;
derive_csi_sequence!("Hide the cursor.", Hide, "?25l");
derive_csi_sequence!("Show the cursor... | fn cursor_pos(&mut self) -> io::Result<(u16, u16)>;
}
impl<W: Write> DetectCursorPos for W {
fn cursor_pos(&mut self) -> io::Result<(u16, u16)> {
let delimiter = b'R';
let mut stdin = async_stdin_until(delimiter);
// Where is the cursor?
// Use `ESC [ 6 n`.
write!(self,... | /// Get the (1,1)-based cursor position from the terminal. | random_line_split |
cursor.rs | //! Cursor movement.
use std::fmt;
use std::ops;
use std::io::{self, Write, Error, ErrorKind, Read};
use async::async_stdin_until;
use std::time::{SystemTime, Duration};
use raw::CONTROL_SEQUENCE_TIMEOUT;
use numtoa::NumToA;
derive_csi_sequence!("Hide the cursor.", Hide, "?25l");
derive_csi_sequence!("Show the cursor... |
}
impl<W: Write> ops::DerefMut for HideCursor<W> {
fn deref_mut(&mut self) -> &mut W {
&mut self.output
}
}
impl<W: Write> Write for HideCursor<W> {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.output.write(buf)
}
fn flush(&mut self) -> io::Result<()> {
sel... | {
&self.output
} | identifier_body |
cursor.rs | //! Cursor movement.
use std::fmt;
use std::ops;
use std::io::{self, Write, Error, ErrorKind, Read};
use async::async_stdin_until;
use std::time::{SystemTime, Duration};
use raw::CONTROL_SEQUENCE_TIMEOUT;
use numtoa::NumToA;
derive_csi_sequence!("Hide the cursor.", Hide, "?25l");
derive_csi_sequence!("Show the cursor... | (&mut self) -> io::Result<()> {
self.output.flush()
}
}
| flush | identifier_name |
cursor.rs | //! Cursor movement.
use std::fmt;
use std::ops;
use std::io::{self, Write, Error, ErrorKind, Read};
use async::async_stdin_until;
use std::time::{SystemTime, Duration};
use raw::CONTROL_SEQUENCE_TIMEOUT;
use numtoa::NumToA;
derive_csi_sequence!("Hide the cursor.", Hide, "?25l");
derive_csi_sequence!("Show the cursor... |
}
if read_chars.is_empty() {
return Err(Error::new(ErrorKind::Other, "Cursor position detection timed out."));
}
// The answer will look like `ESC [ Cy ; Cx R`.
read_chars.pop(); // remove trailing R.
let read_str = String::from_utf8(read_chars).unwrap();
... | {
read_chars.push(buf[0]);
} | conditional_block |
cabi_mips.rs | // Copyright 2012-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-MI... | let mut fields = padding.map_move_default(~[], |p| ~[p]);
if coerce {
fields = vec::append(fields, coerce_to_int(size));
} else {
fields.push(ty);
}
return Type::struct_(fields, false);
}
pub fn compute_abi_info(_ccx: &mut CrateContext,
atys: &[Type],
... | random_line_split | |
cabi_mips.rs | // Copyright 2012-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-MI... |
fn padding_ty(align: uint, offset: uint) -> Option<Type> {
if ((align - 1 ) & offset) > 0 {
return Some(Type::i32());
}
return None;
}
fn coerce_to_int(size: uint) -> ~[Type] {
let int_ty = Type::i32();
let mut args = ~[];
let mut n = size / 32;
while n > 0 {
args.push(i... | {
return match ty.kind() {
Integer
| Pointer
| Float
| Double => true,
_ => false
};
} | identifier_body |
cabi_mips.rs | // Copyright 2012-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-MI... | (off: uint, ty: Type) -> uint {
let a = ty_align(ty);
return align_up_to(off, a);
}
fn ty_align(ty: Type) -> uint {
match ty.kind() {
Integer => {
unsafe {
((llvm::LLVMGetIntTypeWidth(ty.to_ref()) as uint) + 7) / 8
}
}
Pointer => 4,
Fl... | align | identifier_name |
cabi_mips.rs | // Copyright 2012-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-MI... | else { 0 };
for aty in atys.iter() {
let (ty, attr) = classify_arg_ty(*aty, &mut offset);
arg_tys.push(ty);
attrs.push(attr);
};
if sret {
arg_tys = vec::append(~[ret_ty], arg_tys);
attrs = vec::append(~[ret_attr], attrs);
ret_ty = LLVMType { cast: false, t... | { 4 } | conditional_block |
borrowck-freeze-frozen-mut.rs | // run-pass
// Test that a `&mut` inside of an `&` is freezable.
struct MutSlice<'a, T:'a> {
data: &'a mut [T]
}
fn get<'a, T>(ms: &'a MutSlice<'a, T>, index: usize) -> &'a T |
pub fn main() {
let mut data = [1, 2, 3];
{
let slice = MutSlice { data: &mut data };
slice.data[0] += 4;
let index0 = get(&slice, 0);
let index1 = get(&slice, 1);
let index2 = get(&slice, 2);
assert_eq!(*index0, 5);
assert_eq!(*index1, 2);
asser... | {
&ms.data[index]
} | identifier_body |
borrowck-freeze-frozen-mut.rs | // run-pass
// Test that a `&mut` inside of an `&` is freezable.
struct MutSlice<'a, T:'a> {
data: &'a mut [T]
}
| }
pub fn main() {
let mut data = [1, 2, 3];
{
let slice = MutSlice { data: &mut data };
slice.data[0] += 4;
let index0 = get(&slice, 0);
let index1 = get(&slice, 1);
let index2 = get(&slice, 2);
assert_eq!(*index0, 5);
assert_eq!(*index1, 2);
asse... | fn get<'a, T>(ms: &'a MutSlice<'a, T>, index: usize) -> &'a T {
&ms.data[index] | random_line_split |
borrowck-freeze-frozen-mut.rs | // run-pass
// Test that a `&mut` inside of an `&` is freezable.
struct | <'a, T:'a> {
data: &'a mut [T]
}
fn get<'a, T>(ms: &'a MutSlice<'a, T>, index: usize) -> &'a T {
&ms.data[index]
}
pub fn main() {
let mut data = [1, 2, 3];
{
let slice = MutSlice { data: &mut data };
slice.data[0] += 4;
let index0 = get(&slice, 0);
let index1 = get(&sl... | MutSlice | identifier_name |
look_command.rs | use super::{inventory_command::inventory, CommandHelpers, CommandLineProcessor};
use crate::{
actions::{self, ActionOutput},
entity::{EntityRef, Realm},
player_output::PlayerOutput,
relative_direction::RelativeDirection,
utils::{direction_by_abbreviation, is_direction, vector_for_direction},
};
///... | (realm: &mut Realm, player_ref: EntityRef, helpers: CommandHelpers) -> ActionOutput {
let (player, room) = realm.character_and_room_res(player_ref)?;
let processor = helpers.command_line_processor;
let alias = processor.take_word().unwrap();
if alias.starts_with('l') {
if!processor.has_words_l... | look | identifier_name |
look_command.rs | use super::{inventory_command::inventory, CommandHelpers, CommandLineProcessor};
use crate::{
actions::{self, ActionOutput},
entity::{EntityRef, Realm},
player_output::PlayerOutput,
relative_direction::RelativeDirection,
utils::{direction_by_abbreviation, is_direction, vector_for_direction},
};
///... | ..helpers
},
);
}
let description = processor.take_entity_description().ok_or_else(|| {
if alias == "examine" {
"Examine what?".to_owned()
} else {
"Look at what?".to_owned()
}
})?;
if processor.peek_rest() == "in inven... | {
let (player, room) = realm.character_and_room_res(player_ref)?;
let processor = helpers.command_line_processor;
let alias = processor.take_word().unwrap();
if alias.starts_with('l') {
if !processor.has_words_left() {
return actions::look_at_entity(realm, player_ref, player.curren... | identifier_body |
look_command.rs | use super::{inventory_command::inventory, CommandHelpers, CommandLineProcessor};
use crate::{
actions::{self, ActionOutput},
entity::{EntityRef, Realm},
player_output::PlayerOutput,
relative_direction::RelativeDirection,
utils::{direction_by_abbreviation, is_direction, vector_for_direction},
};
///... | command_line_processor: &mut CommandLineProcessor::new(player_ref, "inventory"),
..helpers
},
);
}
let description = processor.take_entity_description().ok_or_else(|| {
if alias == "examine" {
"Examine what?".to_owned()
} else {
... | CommandHelpers { | random_line_split |
look_command.rs | use super::{inventory_command::inventory, CommandHelpers, CommandLineProcessor};
use crate::{
actions::{self, ActionOutput},
entity::{EntityRef, Realm},
player_output::PlayerOutput,
relative_direction::RelativeDirection,
utils::{direction_by_abbreviation, is_direction, vector_for_direction},
};
///... | else {
"Look where?".to_owned()
});
};
let mut output = vec![PlayerOutput::new_from_string(player_ref.id(), output)];
output.append(&mut actions::look_in_direction(
realm, player_ref, &direction,
)?);
outpu... | {
"Examine what?".to_owned()
} | conditional_block |
ffz.rs | use std;
use serde_json;
use serde;
use std::io::Read;
use emote;
use emote::{EmoteError,JsonError};
use http;
const CHANNEL_URL:&str = "https://api.frankerfacez.com/v1/room/";
const GLOBAL_URL:&str = "https://api.frankerfacez.com/v1/set/global";
pub struct Emote<'a>{
http: &'a http::Http,
}
#[derive(Serialize,... | }
impl <'a>Emote<'a>{
pub fn new(client:&http::Http)->Result<Emote,String>{
Ok(Emote{
http:client
})
}
pub fn get_channel(&self,channel:&str)->Result<Vec<Emoticon>,EmoteError>{
let s = try!(self.http.get_body_string(&format!("{}{}",CHANNEL_URL,channel)).map_err(... | pub struct Emoticon{
id:i64,
name:String, | random_line_split |
ffz.rs | use std;
use serde_json;
use serde;
use std::io::Read;
use emote;
use emote::{EmoteError,JsonError};
use http;
const CHANNEL_URL:&str = "https://api.frankerfacez.com/v1/room/";
const GLOBAL_URL:&str = "https://api.frankerfacez.com/v1/set/global";
pub struct Emote<'a>{
http: &'a http::Http,
}
#[derive(Serialize,... | {
display_name:String,
id:String,
set:i64,
twitch_id:i64,
}
#[derive(Serialize, Deserialize)]
pub struct Emoticon{
id:i64,
name:String,
}
impl <'a>Emote<'a>{
pub fn new(client:&http::Http)->Result<Emote,String>{
Ok(Emote{
http:client
})
}
pub fn... | Room | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.