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 |
|---|---|---|---|---|
mod.rs | //public mods
pub mod address_mode;
pub mod opcode_class;
//private mods
use std::clone::Clone;
// hoisted interfaces
#[derive(Default)]
pub struct OpcodeDebugInfo {
pub opcode: u8,
pub name: String,
pub address_mode_name: String,
pub notes: String,
}
#[derive(Default)]
pub struct OpcodeExecInfo {
... | }
}
} | random_line_split | |
cell.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/. */
//! A shareable mutable container for the DOM.
use dom::bindings::trace::JSTraceable;
use js::jsapi::{JSTracer};
... |
/// Mutably borrows the wrapped value.
///
/// The borrow lasts until the returned `RefMut` exits scope. The value
/// cannot be borrowed while this borrow is active.
///
/// Returns `None` if the value is currently borrowed.
///
/// # Panics
///
/// Panics if this is called of... | {
debug_assert!(task_state::get().is_script());
match self.value.borrow_state() {
BorrowState::Writing => None,
_ => Some(self.value.borrow()),
}
} | identifier_body |
cell.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/. */
//! A shareable mutable container for the DOM.
use dom::bindings::trace::JSTraceable;
use js::jsapi::{JSTracer};
... | debug_assert!(task_state::get().is_script());
match self.value.borrow_state() {
BorrowState::Writing => None,
_ => Some(self.value.borrow()),
}
}
/// Mutably borrows the wrapped value.
///
/// The borrow lasts until the returned `RefMut` exits scope. The ... | random_line_split | |
cell.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/. */
//! A shareable mutable container for the DOM.
use dom::bindings::trace::JSTraceable;
use js::jsapi::{JSTracer};
... | <'a>(&'a self) -> Option<RefMut<'a, T>> {
debug_assert!(task_state::get().is_script());
match self.value.borrow_state() {
BorrowState::Unused => Some(self.value.borrow_mut()),
_ => None,
}
}
}
impl<T: JSTraceable> JSTraceable for DOMRefCell<T> {
fn trace(&self, t... | try_borrow_mut | identifier_name |
reader.rs | use std::io;
use std::io::ErrorKind;
use std::marker::PhantomData;
#[derive(Debug, Eq, PartialEq)]
pub enum ReaderStatus<T> {
Pending,
Complete(T)
}
// TODO: implement HasReader for all Messages, ErrorCode,...
pub trait HasReader: Sized {
type Reader: Reader<Self>;
fn reader() -> Self::Reader;
}
///... |
/// Resumes with the given input
pub fn resume<I>(&mut self, input: &mut I) -> io::Result<ReaderStatus<T>> where I: io::Read {
match self.inner.resume(input) {
Ok(status) => match status {
ReaderStatus::Complete(val) => Ok(ReaderStatus::Complete(val)),
Reader... | } | random_line_split |
reader.rs | use std::io;
use std::io::ErrorKind;
use std::marker::PhantomData;
#[derive(Debug, Eq, PartialEq)]
pub enum ReaderStatus<T> {
Pending,
Complete(T)
}
// TODO: implement HasReader for all Messages, ErrorCode,...
pub trait HasReader: Sized {
type Reader: Reader<Self>;
fn reader() -> Self::Reader;
}
///... |
},
Err(err) => {
self.inner.rewind();
return Err(err);
}
};
}
}
} | {} | conditional_block |
reader.rs | use std::io;
use std::io::ErrorKind;
use std::marker::PhantomData;
#[derive(Debug, Eq, PartialEq)]
pub enum ReaderStatus<T> {
Pending,
Complete(T)
}
// TODO: implement HasReader for all Messages, ErrorCode,...
pub trait HasReader: Sized {
type Reader: Reader<Self>;
fn reader() -> Self::Reader;
}
///... | (inner: R) -> Self {
ReaderController { inner, _marker: PhantomData {} }
}
/// Resumes with the given input
pub fn resume<I>(&mut self, input: &mut I) -> io::Result<ReaderStatus<T>> where I: io::Read {
match self.inner.resume(input) {
Ok(status) => match status {
... | new | identifier_name |
reader.rs | use std::io;
use std::io::ErrorKind;
use std::marker::PhantomData;
#[derive(Debug, Eq, PartialEq)]
pub enum ReaderStatus<T> {
Pending,
Complete(T)
}
// TODO: implement HasReader for all Messages, ErrorCode,...
pub trait HasReader: Sized {
type Reader: Reader<Self>;
fn reader() -> Self::Reader;
}
///... |
} | {
loop {
match self.inner.resume(input) {
Ok(status) => match status {
ReaderStatus::Complete(value) => { return Ok(value) }
ReaderStatus::Pending => {}
},
Err(err) => {
self.inner.rewind();
... | identifier_body |
get_addrs.rs | extern crate libnfqueue as nfq;
use nfq::handle::{Handle, ProtocolFamily};
use nfq::queue::{Verdict, VerdictHandler};
use nfq::message::{Message, IPHeader};
fn main() {
let mut handle = Handle::new().ok().unwrap();
handle.bind(ProtocolFamily::INET).ok().unwrap();
let mut queue = handle.queue(0, Decider).... | };
Verdict::Accept
}
} | Err(_) => () | random_line_split |
get_addrs.rs | extern crate libnfqueue as nfq;
use nfq::handle::{Handle, ProtocolFamily};
use nfq::queue::{Verdict, VerdictHandler};
use nfq::message::{Message, IPHeader};
fn main() {
let mut handle = Handle::new().ok().unwrap();
handle.bind(ProtocolFamily::INET).ok().unwrap();
let mut queue = handle.queue(0, Decider).... |
}
| {
println!("Handling packet (ID: {})", message.header.id());
// Note that the queue was set and handle was started with `_sized`
match unsafe { message.ip_header() } {
Ok(ip_header) => println!("saddr: {}, daddr: {}", ip_header.saddr(), ip_header.daddr()),
Err(_) => ()
... | identifier_body |
get_addrs.rs | extern crate libnfqueue as nfq;
use nfq::handle::{Handle, ProtocolFamily};
use nfq::queue::{Verdict, VerdictHandler};
use nfq::message::{Message, IPHeader};
fn main() {
let mut handle = Handle::new().ok().unwrap();
handle.bind(ProtocolFamily::INET).ok().unwrap();
let mut queue = handle.queue(0, Decider).... | ;
impl VerdictHandler for Decider {
fn decide(&mut self, message: &Message) -> Verdict {
println!("Handling packet (ID: {})", message.header.id());
// Note that the queue was set and handle was started with `_sized`
match unsafe { message.ip_header() } {
Ok(ip_header) => println... | Decider | identifier_name |
normalize.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-MI... | (a: char, b: char) -> Option<char> {
compose_hangul(a, b).or_else(|| {
match bsearch_table(a, composition_table) {
None => None,
Some(candidates) => {
match candidates.binary_search(|&(val, _)| {
if b == val { Equal }
else if va... | compose | identifier_name |
normalize.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-MI... |
None => ()
}
// Bottom out if we're not doing compat.
if!k { i(c); return; }
// Then check the compatibility decompositions
match bsearch_table(c, compatibility_table) {
Some(compat) => {
for x in compat.iter() {
d(*x, |b| i(b), k);
}
... | {
for x in canon.iter() {
d(*x, |b| i(b), k);
}
return;
} | conditional_block |
normalize.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-MI... |
/// Compute canonical or compatible Unicode decomposition for character
pub fn decompose_compatible(c: char, i: |char|) { d(c, i, true); }
fn d(c: char, i: |char|, k: bool) {
// 7-bit ASCII never decomposes
if c <= '\x7f' { i(c); return; }
// Perform decomposition for Hangul
if (c as u32) >= S_BASE ... | { d(c, i, false); } | identifier_body |
normalize.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-MI... | else if val < b { Less }
else { Greater }
}) {
slice::BinarySearchResult::Found(idx) => {
let (_, result) = candidates[idx];
Some(result)
}
slice::BinarySea... | None => None,
Some(candidates) => {
match candidates.binary_search(|&(val, _)| {
if b == val { Equal } | random_line_split |
htmlembedelement.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::HTMLEmbedElementBinding;
use dom::bindings::root::DomRoot;
use dom::document::Document;
use dom::htmlelement::HTMLElement;
use dom::node::Node;
use dom_struct::dom_struct;
use html5ever::{LocalName, Prefix};
#[dom_struct]
pub struct HTMLEmbedElement {
htmlelement: HTMLElement... | random_line_split | |
htmlembedelement.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::HTMLEmbedElementBinding;
use dom::bindings::root::DomRoot;
use dom::document... |
#[allow(unrooted_must_root)]
pub fn new(local_name: LocalName,
prefix: Option<Prefix>,
document: &Document) -> DomRoot<HTMLEmbedElement> {
Node::reflect_node(Box::new(HTMLEmbedElement::new_inherited(local_name, prefix, document)),
document,
... | {
HTMLEmbedElement {
htmlelement: HTMLElement::new_inherited(local_name, prefix, document)
}
} | identifier_body |
htmlembedelement.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::HTMLEmbedElementBinding;
use dom::bindings::root::DomRoot;
use dom::document... | (local_name: LocalName, prefix: Option<Prefix>, document: &Document) -> HTMLEmbedElement {
HTMLEmbedElement {
htmlelement: HTMLElement::new_inherited(local_name, prefix, document)
}
}
#[allow(unrooted_must_root)]
pub fn new(local_name: LocalName,
prefix: Option<Pr... | new_inherited | identifier_name |
lib.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 ... | () {}
| fixme_14344_be_sure_to_link_to_collections | identifier_name |
lib.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 ... | {} | identifier_body | |
lib.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 ... | //! performed.
//!
//! This library, like libcore, is not intended for general usage, but rather as
//! a building block of other libraries. The types and interfaces in this
//! library are reexported through the [standard library](../std/index.html),
//! and should not be used through this library.
//!
//! Currently, ... | //!
//! This is the lowest level library through which allocation in Rust can be | random_line_split |
process_samples.rs | use std::{io, fs, env};
use std::io::prelude::*;
use std::path::Path;
#[derive(Debug)]
struct Data {
id: u64,
api_duration: f64,
latency: f64,
gpu_duration: f64,
}
fn parse_csv(line: &str) -> Data {
let mut inside = false;
let mut col = line.trim().split('"').filter(|_| {
inside =!insi... | Ok(())
}
fn main() {
let mut args = env::args().skip(1);
let directory = args.next().unwrap_or_else(|| String::from("samples"));
let results = Path::new(&directory).join("results");
let mut w = io::BufWriter::new(fs::File::create(results).unwrap());
write!(w, "\"Directory\"").unwrap();
Value... | let mut leaf = true;
for entry in try!(fs::read_dir(dir)) {
let entry = try!(entry);
let path = entry.path();
if path.is_dir() {
leaf = false;
try!(visit_dir(&path, file_cb, leaf_cb));
} else {
file_cb(&path, ... | conditional_block |
process_samples.rs | use std::{io, fs, env};
use std::io::prelude::*;
use std::path::Path;
#[derive(Debug)]
struct Data {
id: u64,
api_duration: f64,
latency: f64,
gpu_duration: f64,
}
fn parse_csv(line: &str) -> Data {
let mut inside = false;
let mut col = line.trim().split('"').filter(|_| {
inside =!insi... | // Hypothesis: Sorted By GPU Start Time
let mut prev: Option<Data> = None;
while r.read_line(&mut line).unwrap() > 0 {
let cur = parse_csv(&line);
if let Some(mut p) = prev.take() {
if p.id == cur.id {
if p.latency < cur.latency { p.latency = cur.latency; }
... | line.clear();
}
writeln!(w, "Transfer ID, API Duration(µs), Latency(µs), GPU Duration(µs)").unwrap();
| random_line_split |
process_samples.rs | use std::{io, fs, env};
use std::io::prelude::*;
use std::path::Path;
#[derive(Debug)]
struct Data {
id: u64,
api_duration: f64,
latency: f64,
gpu_duration: f64,
}
fn parse_csv(line: &str) -> Data {
let mut inside = false;
let mut col = line.trim().split('"').filter(|_| {
inside =!insi... | {
let mut args = env::args().skip(1);
let directory = args.next().unwrap_or_else(|| String::from("samples"));
let results = Path::new(&directory).join("results");
let mut w = io::BufWriter::new(fs::File::create(results).unwrap());
write!(w, "\"Directory\"").unwrap();
Value::write_header("API du... | n() | identifier_name |
process_samples.rs | use std::{io, fs, env};
use std::io::prelude::*;
use std::path::Path;
#[derive(Debug)]
struct Data {
id: u64,
api_duration: f64,
latency: f64,
gpu_duration: f64,
}
fn parse_csv(line: &str) -> Data {
let mut inside = false;
let mut col = line.trim().split('"').filter(|_| {
inside =!insi... | fn write_header<W: io::Write>(prefix: &str, w: &mut W) {
write!(w, ",\"{0}{1}\",\"{0}{2}\",\"{0}{3}\",\"{0}{4}\",\"{0}{5}\"",
prefix, "min", "max", "avg", "var", "stddev").unwrap();
}
}
fn process_results<W: io::Write>(directory: &Path, w: &mut W) {
let mut api_duration = Value::new();
... | let avg = self.sum / n;
let var = self.sq_sum / n - avg.powi(2);
write!(w, ",{},{},{},{},{}", self.min, self.max, avg, var, var.sqrt()).unwrap();
}
| identifier_body |
mod.rs | // This file is part of zinc64.
// Copyright (c) 2016-2019 Sebastian Jastrzebski. All rights reserved.
// Licensed under the GPLv3. See LICENSE file in the project root for full license text.
mod help;
mod load;
mod ls;
mod parser;
mod reset;
use std::io::Write;
use std::result::Result;
use zinc64_emu::system::C64;
... | };
handler.run(out)
}
} | random_line_split | |
mod.rs | // This file is part of zinc64.
// Copyright (c) 2016-2019 Sebastian Jastrzebski. All rights reserved.
// Licensed under the GPLv3. See LICENSE file in the project root for full license text.
mod help;
mod load;
mod ls;
mod parser;
mod reset;
use std::io::Write;
use std::result::Result;
use zinc64_emu::system::C64;
... | {
Help(Option<String>),
Load(String),
Ls(Option<String>),
Reset(bool),
}
trait Handler {
fn run(&mut self, out: &mut dyn Write) -> Result<(), String>;
}
pub struct Executor {
parser: Parser,
}
impl Executor {
pub fn new() -> Self {
Executor {
parser: Parser::new(),
... | Cmd | identifier_name |
mod.rs | // This file is part of zinc64.
// Copyright (c) 2016-2019 Sebastian Jastrzebski. All rights reserved.
// Licensed under the GPLv3. See LICENSE file in the project root for full license text.
mod help;
mod load;
mod ls;
mod parser;
mod reset;
use std::io::Write;
use std::result::Result;
use zinc64_emu::system::C64;
... |
}
| {
let command = self.parser.parse(input)?;
let mut handler: Box<dyn Handler> = match command {
Cmd::Load(path) => Box::new(LoadCommand::new(c64, path)),
Cmd::Ls(path) => Box::new(LsCommand::new(path)),
Cmd::Reset(hard) => Box::new(ResetCommand::new(c64, hard)),
... | identifier_body |
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(box_syntax)]
#![feature(custom_attribute)]
#![feature(custom_derive)]
#![feature(plugin)]
#![feature(sl... | {
/// An HTTP API
HTTP,
/// A non-HTTP API
NonHTTP,
}
/// Messages sent in response to a `Load` message
#[derive(PartialEq, Debug, Deserialize, Serialize)]
pub enum ProgressMsg {
/// Binary data - there may be multiple of these
Payload(Vec<u8>),
/// Indicates loading is complete, either su... | CookieSource | 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(box_syntax)]
#![feature(custom_attribute)]
#![feature(custom_derive)]
#![feature(plugin)]
#![feature(sl... | https_state: response::HttpsState::None,
}
}
/// Extract the parts of a Mime that we care about.
pub fn set_content_type(&mut self, content_type: Option<&Mime>) {
match self.headers {
None => self.headers = Some(Headers::new()),
Some(_) => (),
}
... | random_line_split | |
read_line.rs | //!
//! Reads a line of text from a stream
//!
use std::result::Result;
use std::error::Error;
use std::io::*;
use std::sync::*;
use serde_json::*;
use gossyp_base::*;
#[derive(Serialize, Deserialize)]
pub struct ReadLineResult {
pub eof: bool,
pub line: String
}
///
/// Tool for reading text from a str... |
// Keep building the result otherwise
result_utf8.push(chr[0]);
}
// Generate the final result
Ok(json![{
"eof": reached_eof,
"line": String::from_utf8_lossy(&result_utf8)
}])
}
}
| {
reached_eof = false;
break;
} | conditional_block |
read_line.rs | //!
//! Reads a line of text from a stream
//!
use std::result::Result;
use std::error::Error;
use std::io::*;
use std::sync::*;
use serde_json::*;
use gossyp_base::*;
#[derive(Serialize, Deserialize)]
pub struct ReadLineResult {
pub eof: bool,
pub line: String
}
///
/// Tool for reading text from a str... | }
} | }]) | random_line_split |
read_line.rs | //!
//! Reads a line of text from a stream
//!
use std::result::Result;
use std::error::Error;
use std::io::*;
use std::sync::*;
use serde_json::*;
use gossyp_base::*;
#[derive(Serialize, Deserialize)]
pub struct ReadLineResult {
pub eof: bool,
pub line: String
}
///
/// Tool for reading text from a str... | (stream: Stream) -> ReadLineTool<Stream> {
ReadLineTool { stream: Mutex::new(stream) }
}
}
impl<Stream:'static+Read+Send> Tool for ReadLineTool<Stream> {
fn invoke_json(&self, _input: Value, _environment: &Environment) -> Result<Value, Value> {
// We hold the stream until we've read the entire ... | new_with_stream | identifier_name |
event.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::EventBinding;
use dom::bindings::codegen::EventBinding::EventConstants;
use dom::bindi... | target: None,
phase: PhaseNone,
type_: ~"",
default_prevented: false,
cancelable: true,
bubbles: true,
trusted: false,
dispatching: false,
stop_propagation: false,
stop_immediate: false,
i... | current_target: None, | random_line_split |
event.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::EventBinding;
use dom::bindings::codegen::EventBinding::EventConstants;
use dom::bindi... |
}
pub fn StopPropagation(&mut self) {
self.stop_propagation = true;
}
pub fn StopImmediatePropagation(&mut self) {
self.stop_immediate = true;
self.stop_propagation = true;
}
pub fn Bubbles(&self) -> bool {
self.bubbles
}
pub fn Cancelable(&self) -> b... | {
self.default_prevented = true
} | conditional_block |
event.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::EventBinding;
use dom::bindings::codegen::EventBinding::EventConstants;
use dom::bindi... | (&self) -> bool {
self.cancelable
}
pub fn TimeStamp(&self) -> u64 {
0
}
pub fn InitEvent(&mut self,
type_: DOMString,
bubbles: bool,
cancelable: bool) {
self.type_ = type_;
self.cancelable = cancelable;
... | Cancelable | identifier_name |
event.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::EventBinding;
use dom::bindings::codegen::EventBinding::EventConstants;
use dom::bindi... |
}
| {
&mut self.reflector_
} | identifier_body |
filter_next.rs | use clippy_utils::diagnostics::{span_lint, span_lint_and_sugg};
use clippy_utils::is_trait_method;
use clippy_utils::source::snippet;
use rustc_errors::Applicability;
use rustc_hir as hir;
use rustc_lint::LateContext;
use rustc_span::sym;
use super::FILTER_NEXT;
/// lint use of `filter().next()` for `Iterators`
pub(s... | <'tcx>(
cx: &LateContext<'tcx>,
expr: &'tcx hir::Expr<'_>,
recv: &'tcx hir::Expr<'_>,
filter_arg: &'tcx hir::Expr<'_>,
) {
// lint if caller of `.filter().next()` is an Iterator
if is_trait_method(cx, expr, sym::Iterator) {
let msg = "called `filter(..).next()` on an `Iterator`. This is ... | check | identifier_name |
filter_next.rs | use clippy_utils::diagnostics::{span_lint, span_lint_and_sugg};
use clippy_utils::is_trait_method;
use clippy_utils::source::snippet;
use rustc_errors::Applicability;
use rustc_hir as hir;
use rustc_lint::LateContext;
use rustc_span::sym;
use super::FILTER_NEXT;
/// lint use of `filter().next()` for `Iterators`
pub(s... | else {
span_lint(cx, FILTER_NEXT, expr.span, msg);
}
}
}
| {
let iter_snippet = snippet(cx, recv.span, "..");
// add note if not multi-line
span_lint_and_sugg(
cx,
FILTER_NEXT,
expr.span,
msg,
"try this",
format!("{}.find({})", iter_snippet, filte... | conditional_block |
filter_next.rs | use clippy_utils::diagnostics::{span_lint, span_lint_and_sugg};
use clippy_utils::is_trait_method;
use clippy_utils::source::snippet;
use rustc_errors::Applicability;
use rustc_hir as hir;
use rustc_lint::LateContext;
use rustc_span::sym;
use super::FILTER_NEXT;
/// lint use of `filter().next()` for `Iterators`
pub(s... | }
}
}
| {
// lint if caller of `.filter().next()` is an Iterator
if is_trait_method(cx, expr, sym::Iterator) {
let msg = "called `filter(..).next()` on an `Iterator`. This is more succinctly expressed by calling \
`.find(..)` instead";
let filter_snippet = snippet(cx, filter_arg.span,... | identifier_body |
filter_next.rs | use clippy_utils::diagnostics::{span_lint, span_lint_and_sugg};
use clippy_utils::is_trait_method;
use clippy_utils::source::snippet;
use rustc_errors::Applicability;
use rustc_hir as hir;
use rustc_lint::LateContext;
use rustc_span::sym;
use super::FILTER_NEXT;
/// lint use of `filter().next()` for `Iterators`
pub(s... | } | random_line_split | |
test_utils.rs | // Copyright 2016 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License,
// version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which
// licence you accepted on initial access to the Software (the "Licences").
//
// By ... | <F, E, T, U>(f: F) -> Result<Vec<T>, i32>
where
F: FnOnce(*mut c_void,
extern "C" fn(user_data: *mut c_void, result: FfiResult, T::C, usize)),
E: Debug,
T: ReprC<C = *const U, Error = E>,
{
let (tx, rx) = mpsc::channel::<SendWrapper<Result<Vec<T>, i32>>>();
f(sender_as_user_data(&tx), ca... | call_vec | identifier_name |
test_utils.rs | // Copyright 2016 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License,
// version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which
// licence you accepted on initial access to the Software (the "Licences").
//
// By ... | where
T: Send,
{
let tx = user_data as *mut Sender<T>;
unwrap!((*tx).send(value));
}
/// Call a FFI function and block until its callback gets called.
/// Use this if the callback accepts no arguments in addition to `user_data`
/// and `error_code`.
pub fn call_0<F>(f: F) -> Result<(), i32>
where
F: Fn... | }
/// Send through a `mpsc::Sender` pointed to by the user data pointer.
pub unsafe fn send_via_user_data<T>(user_data: *mut c_void, value: T) | random_line_split |
test_utils.rs | // Copyright 2016 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License,
// version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which
// licence you accepted on initial access to the Software (the "Licences").
//
// By ... | else { Err(error) }
}
/// Call an FFI function and block until its callback gets called, then return
/// the argument which were passed to that callback.
/// Use this if the callback accepts one argument in addition to `user_data`
/// and `error_code`.
pub unsafe fn call_1<F, E: Debug, T>(f: F) -> Result<T, i32>
wher... | { Ok(()) } | conditional_block |
test_utils.rs | // Copyright 2016 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License,
// version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which
// licence you accepted on initial access to the Software (the "Licences").
//
// By ... |
/// Call an FFI function and block until its callback gets called, then return
/// the argument which were passed to that callback.
/// Use this if the callback accepts one argument in addition to `user_data`
/// and `error_code`.
pub unsafe fn call_1<F, E: Debug, T>(f: F) -> Result<T, i32>
where
F: FnOnce(*mut c... | {
let (tx, rx) = mpsc::channel::<i32>();
f(sender_as_user_data(&tx), callback_0);
let error = unwrap!(rx.recv());
if error == 0 { Ok(()) } else { Err(error) }
} | identifier_body |
edge_case.rs | // edition:2021
#![feature(rustc_attrs)]
#![allow(unused)]
#![allow(dead_code)]
struct Int(i32);
struct B<'a>(&'a i32);
const I : Int = Int(0);
const REF_I : &'static Int = &I;
struct MyStruct<'a> {
a: &'static Int,
b: B<'a>,
}
fn foo<'a, 'b>(m: &'a MyStruct<'b>) -> impl FnMut() +'static {
let c = #[rus... | } | fn main() {
let t = 0;
let s = MyStruct { a: REF_I, b: B(&t) };
let _ = foo(&s); | random_line_split |
edge_case.rs | // edition:2021
#![feature(rustc_attrs)]
#![allow(unused)]
#![allow(dead_code)]
struct Int(i32);
struct B<'a>(&'a i32);
const I : Int = Int(0);
const REF_I : &'static Int = &I;
struct MyStruct<'a> {
a: &'static Int,
b: B<'a>,
}
fn foo<'a, 'b>(m: &'a MyStruct<'b>) -> impl FnMut() +'static {
let c = #[rus... | {
let t = 0;
let s = MyStruct { a: REF_I, b: B(&t) };
let _ = foo(&s);
} | identifier_body | |
edge_case.rs | // edition:2021
#![feature(rustc_attrs)]
#![allow(unused)]
#![allow(dead_code)]
struct Int(i32);
struct B<'a>(&'a i32);
const I : Int = Int(0);
const REF_I : &'static Int = &I;
struct MyStruct<'a> {
a: &'static Int,
b: B<'a>,
}
fn foo<'a, 'b>(m: &'a MyStruct<'b>) -> impl FnMut() +'static {
let c = #[rus... | () {
let t = 0;
let s = MyStruct { a: REF_I, b: B(&t) };
let _ = foo(&s);
}
| main | identifier_name |
basic.rs | extern crate central;
#[macro_use]
extern crate log;
extern crate env_logger;
use central::types::{Storage, Handle};
use std::collections::HashMap; | use std::thread;
use std::convert::Into;
#[derive(Debug)]
pub struct Credential {
pub user: String,
pub password: String
}
impl Into<String> for Credential {
fn into(self) -> String {
format!("{}:{}", self.user, self.password)
}
}
#[test]
fn test_central_publish() {
let _ = env_logger:... | use std::time::Duration; | random_line_split |
basic.rs | extern crate central;
#[macro_use]
extern crate log;
extern crate env_logger;
use central::types::{Storage, Handle};
use std::collections::HashMap;
use std::time::Duration;
use std::thread;
use std::convert::Into;
#[derive(Debug)]
pub struct Credential {
pub user: String,
pub password: String
}
impl Into<St... |
}
#[test]
fn test_central_publish() {
let _ = env_logger::init();
let credential = Credential {
user: String::from("test"),
password: String::from("test")
};
let mut handlers : HashMap<String, Handle> = HashMap::new();
handlers.insert(String::from("hello"), Box::new(move |... | {
format!("{}:{}", self.user, self.password)
} | identifier_body |
basic.rs | extern crate central;
#[macro_use]
extern crate log;
extern crate env_logger;
use central::types::{Storage, Handle};
use std::collections::HashMap;
use std::time::Duration;
use std::thread;
use std::convert::Into;
#[derive(Debug)]
pub struct Credential {
pub user: String,
pub password: String
}
impl Into<St... | () {
let _ = env_logger::init();
let credential = Credential {
user: String::from("test"),
password: String::from("test")
};
let mut handlers : HashMap<String, Handle> = HashMap::new();
handlers.insert(String::from("hello"), Box::new(move |value: Result<String, ()>| {
... | test_central_publish | identifier_name |
blocks.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 ... | ast_map::NodeItem(i) => match i.node {
ast::ItemFn(ref decl, unsafety, constness, abi, ref generics, ref block) =>
item_fn(ItemFnParts {
id: i.id,
ident: i.ident,
decl: &**decl,
... | match self.node { | random_line_split |
blocks.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 ... | (&self) -> ast::NodeId {
match *self {
FnLikeCode(node) => node.id(),
BlockCode(block) => block.id,
}
}
/// Attempts to construct a Code from presumed FnLike or Block node input.
pub fn from_node(node: Node) -> Option<Code> {
if let ast_map::NodeBlock(block) ... | id | identifier_name |
stringmap.rs | use std::collections::HashMap;
use std::collections::hash_map::Entry::{Occupied, Vacant};
pub fn run() | }
// Iterate the values mutably.
// The iterator element type is &'a mut V. In this case, &mut String.
// So we can append to the strings.
for v in hash.values_mut() {
println!("v = {}", v);
v.push_str(" suffix");
}
// Dumping again shows we did append all the values.
f... | {
println!("********* HashMap<i32, String> examples *********");
let mut hash : HashMap<i32, String> = HashMap::new();
hash.insert(0, String::from("hello"));
hash.insert(1, String::from("world"));
hash.insert(2, String::from("a"));
hash.insert(3, String::from("z"));
hash.insert(4, String::f... | identifier_body |
stringmap.rs | use std::collections::HashMap;
use std::collections::hash_map::Entry::{Occupied, Vacant};
pub fn run() {
println!("********* HashMap<i32, String> examples *********");
let mut hash : HashMap<i32, String> = HashMap::new();
hash.insert(0, String::from("hello"));
hash.insert(1, String::from("world"));
... |
// Drain gives us an iterator of tuples (like iter()).
// After we use the iterator, the hash is empty.
let d : Vec<_> = hash.drain().collect();
println!("After drain, the hash has {} entries", hash.len());
} | random_line_split | |
stringmap.rs | use std::collections::HashMap;
use std::collections::hash_map::Entry::{Occupied, Vacant};
pub fn | () {
println!("********* HashMap<i32, String> examples *********");
let mut hash : HashMap<i32, String> = HashMap::new();
hash.insert(0, String::from("hello"));
hash.insert(1, String::from("world"));
hash.insert(2, String::from("a"));
hash.insert(3, String::from("z"));
hash.insert(4, String... | run | identifier_name |
mod.rs | // Zinc, the bare metal stack for rust.
// Copyright 2014 Ben Gamari <bgamari@gmail.com>
//
// 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... | // See the License for the specific language governing permissions and
// limitations under the License.
use std::gc::Gc;
use syntax::ast;
use syntax::ast::P;
use syntax::ext::base::ExtCtxt;
use node;
mod utils;
mod setter;
mod getter;
mod union;
mod register;
mod accessors;
pub struct Builder {
items: Vec<Gc<ast... | //
// 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. | random_line_split |
mod.rs | // Zinc, the bare metal stack for rust.
// Copyright 2014 Ben Gamari <bgamari@gmail.com>
//
// 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... |
pub fn push_item(&mut self, item: Gc<ast::Item>) {
self.items.push(item);
}
}
| {
node::visit_reg(&*reg, &mut setter::BuildSetters::new(self, cx));
node::visit_reg(&*reg, &mut getter::BuildGetters::new(self, cx));
node::visit_reg(&*reg, &mut register::BuildRegStructs::new(self, cx));
node::visit_reg(&*reg, &mut union::BuildUnionTypes::new(self, cx));
node::visit_reg(&*reg, &mut... | identifier_body |
mod.rs | // Zinc, the bare metal stack for rust.
// Copyright 2014 Ben Gamari <bgamari@gmail.com>
//
// 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... | () -> Builder {
Builder {items: Vec::new()}
}
pub fn emit_items<'a>(&mut self, cx: &'a ExtCtxt, reg: Gc<node::Reg>)
-> Vec<P<ast::Item>> {
node::visit_reg(&*reg, &mut setter::BuildSetters::new(self, cx));
node::visit_reg(&*reg, &mut getter::BuildGetters::new(self, cx));
node::vi... | new | identifier_name |
framing.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use bytes::BytesMut;
use futures::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
use std::{convert::TryInto, io::Result};
/// Read a u16 length prefixed frame from `Stream` into `buf`.
pub async fn read_u16frame<'stream, 'bu... | () {
let (mut a, b) = MemorySocket::new_pair();
drop(b);
let result = block_on(a.write_all(&[42]));
assert!(result.is_err(), true);
}
#[test]
fn write_read_u16frame() -> Result<()> {
let (mut a, mut b) = MemorySocket::new_pair();
block_on(write_u16frame(&mu... | write_u16frame_len_eof | identifier_name |
framing.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use bytes::BytesMut;
use futures::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
use std::{convert::TryInto, io::Result};
/// Read a u16 length prefixed frame from `Stream` into `buf`.
pub async fn read_u16frame<'stream, 'bu... |
/// Write a u16 `len` as BE bytes to `stream`.
///
/// Caller is responsible for flushing the write to `stream`.
async fn write_u16frame_len<TSocket>(stream: &mut TSocket, len: u16) -> Result<()>
where
TSocket: AsyncWrite + Unpin,
{
let len = u16::to_be_bytes(len);
stream.write_all(&len).await?;
Ok((... | {
let len = buf
.len()
.try_into()
.map_err(|_e| std::io::Error::new(std::io::ErrorKind::Other, "Too big"))?;
write_u16frame_len(&mut stream, len).await?;
stream.write_all(buf).await?;
Ok(())
} | identifier_body |
framing.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use bytes::BytesMut;
use futures::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
use std::{convert::TryInto, io::Result};
/// Read a u16 length prefixed frame from `Stream` into `buf`. | buf: &'buf mut BytesMut,
) -> Result<()>
where
'stream: 'c,
'buf: 'c,
TSocket: AsyncRead + Unpin,
{
let len = read_u16frame_len(&mut stream).await?;
buf.resize(len as usize, 0);
stream.read_exact(buf.as_mut()).await?;
Ok(())
}
/// Read a u16 (encoded as BE bytes) from `Stream` and return... | pub async fn read_u16frame<'stream, 'buf, 'c, TSocket>(
mut stream: &'stream mut TSocket, | random_line_split |
font_template.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 core_graphics::data_provider::CGDataProvider;
use core_graphics::font::CGFont;
use core_text::font::CTFont;
us... | {
pub ctfont: Option<CTFont>,
pub identifier: String,
pub font_data: Option<Vec<u8>>
}
unsafe impl Send for FontTemplateData {}
unsafe impl Sync for FontTemplateData {}
impl FontTemplateData {
pub fn new(identifier: &str, font_data: Option<Vec<u8>>) -> FontTemplateData {
let ctfont = match fo... | FontTemplateData | identifier_name |
font_template.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 core_graphics::data_provider::CGDataProvider;
use core_graphics::font::CGFont;
use core_text::font::CTFont;
us... | pub ctfont: Option<CTFont>,
pub identifier: String,
pub font_data: Option<Vec<u8>>
}
unsafe impl Send for FontTemplateData {}
unsafe impl Sync for FontTemplateData {}
impl FontTemplateData {
pub fn new(identifier: &str, font_data: Option<Vec<u8>>) -> FontTemplateData {
let ctfont = match font_... | random_line_split | |
font_template.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 core_graphics::data_provider::CGDataProvider;
use core_graphics::font::CGFont;
use core_text::font::CTFont;
us... | }
}
| {
let ctfont = match font_data {
Some(ref bytes) => {
let fontprov = CGDataProvider::from_buffer(bytes.as_slice());
let cgfont_result = CGFont::from_data_provider(fontprov);
match cgfont_result {
Ok(cgfont) => Some(core_text::font::... | identifier_body |
table.rs | use super::entry::{Entry, EntryFlags};
use super::{ENTRY_COUNT};
use core::ops::{Index, IndexMut};
use core::marker::PhantomData;
use memory::FrameAllocator;
pub const P4: *mut Table<Level4> = 0xffffffff_fffff000 as *mut _;
pub trait TableLevel {}
pub enum Level4 {}
pub enum | {}
pub enum Level2 {}
pub enum Level1 {}
impl TableLevel for Level4 {}
impl TableLevel for Level3 {}
impl TableLevel for Level2 {}
impl TableLevel for Level1 {}
pub trait HierarchicalLevel: TableLevel {
type NextLevel: TableLevel;
}
impl HierarchicalLevel for Level4 {
type NextLevel = Level3;
}
impl Hierarc... | Level3 | identifier_name |
table.rs | use super::entry::{Entry, EntryFlags};
use super::{ENTRY_COUNT};
use core::ops::{Index, IndexMut};
use core::marker::PhantomData;
use memory::FrameAllocator;
pub const P4: *mut Table<Level4> = 0xffffffff_fffff000 as *mut _;
pub trait TableLevel {}
pub enum Level4 {}
pub enum Level3 {}
pub enum Level2 {}
pub enum Lev... | type NextLevel = Level3;
}
impl HierarchicalLevel for Level3 {
type NextLevel = Level2;
}
impl HierarchicalLevel for Level2 {
type NextLevel = Level1;
}
pub struct Table<L: TableLevel> {
entries: [Entry; ENTRY_COUNT],
level: PhantomData<L>,
}
impl<L> Index<usize> for Table<L> where L: TableLevel {... | random_line_split | |
table.rs | use super::entry::{Entry, EntryFlags};
use super::{ENTRY_COUNT};
use core::ops::{Index, IndexMut};
use core::marker::PhantomData;
use memory::FrameAllocator;
pub const P4: *mut Table<Level4> = 0xffffffff_fffff000 as *mut _;
pub trait TableLevel {}
pub enum Level4 {}
pub enum Level3 {}
pub enum Level2 {}
pub enum Lev... |
self.next_table_mut(index).unwrap()
}
} | {
assert!(!self[index].flags().contains(EntryFlags::HUGE_PAGE),
"next_table_create does not support huge pages");
let frame = allocator.allocate_frame().expect("No frames available");
self.entries[index].set(frame, EntryFlags::PRESENT | EntryFlags::WRITEABLE);
... | conditional_block |
table.rs | use super::entry::{Entry, EntryFlags};
use super::{ENTRY_COUNT};
use core::ops::{Index, IndexMut};
use core::marker::PhantomData;
use memory::FrameAllocator;
pub const P4: *mut Table<Level4> = 0xffffffff_fffff000 as *mut _;
pub trait TableLevel {}
pub enum Level4 {}
pub enum Level3 {}
pub enum Level2 {}
pub enum Lev... |
pub fn next_table_create<A>(&mut self, index: usize, allocator: &mut A) -> &mut Table<L::NextLevel> where A: FrameAllocator {
if self.next_table(index).is_none() {
assert!(!self[index].flags().contains(EntryFlags::HUGE_PAGE),
"next_table_create does not support huge pages")... | {
self.next_table_address(index).map(|address| unsafe { &mut *(address as *mut _) })
} | identifier_body |
mesh.rs | use crate::objects::node;
use kiss3d::resource;
use kiss3d::scene::SceneNode;
use kiss3d::window::Window;
use na::{self, Isometry3, Point3, RealField, Vector3};
use ncollide::shape::TriMesh;
use nphysics::math::Isometry;
use nphysics::object::{ColliderAnchor, DefaultColliderHandle, DefaultColliderSet};
use std::cell::R... |
}
pub fn scene_node(&self) -> &SceneNode {
&self.gfx
}
pub fn scene_node_mut(&mut self) -> &mut SceneNode {
&mut self.gfx
}
pub fn object(&self) -> DefaultColliderHandle {
self.collider
}
}
| {
if let ColliderAnchor::OnDeformableBody { .. } = c.anchor() {
let shape = c.shape().as_shape::<TriMesh<N>>().unwrap();
let vtx = shape.points();
self.gfx.modify_vertices(&mut |vertices| {
for (v, new_v) in vertices.iter_mut().zip(vtx.ite... | conditional_block |
mesh.rs | use crate::objects::node;
use kiss3d::resource;
use kiss3d::scene::SceneNode;
use kiss3d::window::Window;
use na::{self, Isometry3, Point3, RealField, Vector3};
use ncollide::shape::TriMesh;
use nphysics::math::Isometry;
use nphysics::object::{ColliderAnchor, DefaultColliderHandle, DefaultColliderSet};
use std::cell::R... | res.gfx.set_surface_rendering_activation(false);
res.gfx.set_lines_width(1.0);
}
let pos: Isometry<f64> =
na::convert_unchecked(*colliders.get(collider).unwrap().position());
let pos: Isometry<f32> = na::convert(pos);
res.gfx.enable_backface_culling(... | {
let vs = vertices;
let is = indices.into_iter().map(na::convert).collect();
let mesh = resource::Mesh::new(vs, is, None, None, false);
let mut res = Mesh {
color,
base_color: color,
delta,
gfx: window.add_mesh(Rc::new(RefCell::new(mesh)... | identifier_body |
mesh.rs | use crate::objects::node;
use kiss3d::resource;
use kiss3d::scene::SceneNode;
use kiss3d::window::Window;
use na::{self, Isometry3, Point3, RealField, Vector3};
use ncollide::shape::TriMesh;
use nphysics::math::Isometry;
use nphysics::object::{ColliderAnchor, DefaultColliderHandle, DefaultColliderSet};
use std::cell::R... |
self.gfx.modify_vertices(&mut |vertices| {
for (v, new_v) in vertices.iter_mut().zip(vtx.iter()) {
*v = na::convert::<Point3<f64>, Point3<f32>>(na::convert_unchecked(*new_v));
}
});
self.gfx.recompute_normal... | // FIXME: don't update if it did not move.
if let Some(c) = colliders.get(self.collider) {
if let ColliderAnchor::OnDeformableBody { .. } = c.anchor() {
let shape = c.shape().as_shape::<TriMesh<N>>().unwrap();
let vtx = shape.points(); | random_line_split |
mesh.rs | use crate::objects::node;
use kiss3d::resource;
use kiss3d::scene::SceneNode;
use kiss3d::window::Window;
use na::{self, Isometry3, Point3, RealField, Vector3};
use ncollide::shape::TriMesh;
use nphysics::math::Isometry;
use nphysics::object::{ColliderAnchor, DefaultColliderHandle, DefaultColliderSet};
use std::cell::R... | <N: RealField>(
collider: DefaultColliderHandle,
colliders: &DefaultColliderSet<N>,
delta: Isometry3<f32>,
vertices: Vec<Point3<f32>>,
indices: Vec<Point3<u32>>,
color: Point3<f32>,
window: &mut Window,
) -> Mesh {
let vs = vertices;
let is = i... | new | identifier_name |
box.rs | // https://rustbyexample.com/std/box.html
// http://rust-lang-ja.org/rust-by-example/std/box.html
use std::mem;
#[allow(dead_code)]
#[derive(Debug, Clone, Copy)]
struct Point {
x: f64,
y: f64,
}
#[allow(dead_code)]
struct Rectangle {
p1: Point,
p2: Point,
}
fn | () -> Point {
Point { x: 0.0, y: 0.0 }
}
fn boxed_origin() -> Box<Point> {
// Allocate this point in the heap, and return a pointer to it
Box::new(Point { x: 0.0, y: 0.0 })
}
fn main() {
// (all the type annotations are superfluous)
// Stack allocated variables
let point: Point = origin();
... | origin | identifier_name |
box.rs | // https://rustbyexample.com/std/box.html
// http://rust-lang-ja.org/rust-by-example/std/box.html
use std::mem;
#[allow(dead_code)]
#[derive(Debug, Clone, Copy)]
struct Point {
x: f64,
y: f64,
}
#[allow(dead_code)]
struct Rectangle {
p1: Point,
p2: Point,
}
fn origin() -> Point {
Point { x: 0.0,... | };
// Heap allocated rectangle
let boxed_rectangle: Box<Rectangle> = Box::new(Rectangle {
p1: origin(),
p2: origin()
});
// The output of functions can be boxed
let boxed_point: Box<Point> = Box::new(origin());
// Double indirection
let box_in_a_box: Box<Box<Point>> = ... | p1: origin(),
p2: Point { x: 3.0, y: 4.0 } | random_line_split |
cstore.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-MI... | else {
f(cpath.as_slice())
}
}
pub fn update_local_path<'a, 'b>(&self, candidate: ast_map::PathElems<'a, 'b>) {
let mut cpath = self.local_path.borrow_mut();
let cap = cpath.len();
match cap {
0 => *cpath = candidate.collect(),
1 => (),
... | {
let name = ast_map::PathMod(token::intern(&self.name));
f(&[name])
} | conditional_block |
cstore.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-MI... | use syntax::codemap;
use syntax::parse::token;
use syntax::parse::token::IdentInterner;
use syntax::util::small_vector::SmallVector;
use ast_map;
// A map from external crate numbers (as decoded from some crate file) to
// local crate numbers (as generated during this session). Each external
// crate may refer to type... | random_line_split | |
cstore.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-MI... |
pub fn name(&self) -> String { decoder::get_crate_name(self.data()) }
pub fn hash(&self) -> Svh { decoder::get_crate_hash(self.data()) }
pub fn imported_filemaps<'a>(&'a self, codemap: &codemap::CodeMap)
-> Ref<'a, Vec<ImportedFileMap>> {
let filemaps = self.codemap... | { self.data.as_slice() } | identifier_body |
cstore.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-MI... | <'a>(&'a self) -> &'a [u8] { self.data.as_slice() }
pub fn name(&self) -> String { decoder::get_crate_name(self.data()) }
pub fn hash(&self) -> Svh { decoder::get_crate_hash(self.data()) }
pub fn imported_filemaps<'a>(&'a self, codemap: &codemap::CodeMap)
-> Ref<'a, Vec<Impo... | data | identifier_name |
cleanup-shortcircuit.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 ... |
}
| {
// Raise a segfault.
unsafe { *(0 as *mut int) = 0; }
} | conditional_block |
cleanup-shortcircuit.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 ... | // expression was the end of the `if`, and as the `"signal".to_owned()`
// expression was never evaluated, we wound up trying to clean
// uninitialized memory.
if args.len() >= 2 && args[1] == "signal".to_owned() {
// Raise a segfault.
unsafe { *(0 as *mut int) = 0; }
}
} | // Here, the rvalue `"signal".to_owned()` requires cleanup. Older versions
// of the code had a problem that the cleanup scope for this | random_line_split |
cleanup-shortcircuit.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 ... | {
let args = os::args();
let args = args.as_slice();
// Here, the rvalue `"signal".to_owned()` requires cleanup. Older versions
// of the code had a problem that the cleanup scope for this
// expression was the end of the `if`, and as the `"signal".to_owned()`
// expression was never evaluated,... | identifier_body | |
cleanup-shortcircuit.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 ... | () {
let args = os::args();
let args = args.as_slice();
// Here, the rvalue `"signal".to_owned()` requires cleanup. Older versions
// of the code had a problem that the cleanup scope for this
// expression was the end of the `if`, and as the `"signal".to_owned()`
// expression was never evaluat... | main | identifier_name |
volumetric_cuboid.rs | use std::ops::{Index, IndexMut};
use num::Zero;
use na::{Pnt2, Pnt3, Mat1, Mat3, Orig, Iterable};
use na;
use ncollide::shape::{Cuboid2, Cuboid3};
use ncollide::math::Scalar;
use volumetric::Volumetric;
/// The volume of a cuboid.
#[inline]
pub fn cuboid_volume<N, V>(dim: usize, half_extents: &V) -> N
where N: Sc... |
let mut res = na::zero::<I>();
res[(0, 0)] = iy + iz;
res[(1, 1)] = ix + iz;
res[(2, 2)] = ix + iy;
res
}
_ => unreachable!()
}
}
macro_rules! impl_volumetric_cuboid(
($t: ident, $dim: expr, $p: ident, $i: ident) => (
impl<N... | random_line_split | |
volumetric_cuboid.rs | use std::ops::{Index, IndexMut};
use num::Zero;
use na::{Pnt2, Pnt3, Mat1, Mat3, Orig, Iterable};
use na;
use ncollide::shape::{Cuboid2, Cuboid3};
use ncollide::math::Scalar;
use volumetric::Volumetric;
/// The volume of a cuboid.
#[inline]
pub fn cuboid_volume<N, V>(dim: usize, half_extents: &V) -> N
where N: Sc... | let _i12: N = na::cast(1.0f64 / 12.0);
let w = _i12 * _2 * _2;
let ix = w * half_extents[0] * half_extents[0];
let iy = w * half_extents[1] * half_extents[1];
let iz = w * half_extents[2] * half_extents[2];
let mut res = na::z... | {
assert!(dim == 2 || dim == 3);
match dim {
2 => {
let _2: N = na::cast(2.0f64);
let _i12: N = na::cast(1.0f64 / 12.0);
let w = _i12 * _2 * _2;
let ix = w * half_extents[0] * half_extents[0];
let iy = w * half_extents[1] * h... | identifier_body |
volumetric_cuboid.rs | use std::ops::{Index, IndexMut};
use num::Zero;
use na::{Pnt2, Pnt3, Mat1, Mat3, Orig, Iterable};
use na;
use ncollide::shape::{Cuboid2, Cuboid3};
use ncollide::math::Scalar;
use volumetric::Volumetric;
/// The volume of a cuboid.
#[inline]
pub fn cuboid_volume<N, V>(dim: usize, half_extents: &V) -> N
where N: Sc... | <P: Orig>() -> P {
na::orig()
}
/// The unit angular inertia of a cuboid.
#[inline]
pub fn cuboid_unit_angular_inertia<N, V, I>(dim: usize, half_extents: &V) -> I
where N: Scalar,
V: Index<usize, Output = N>,
I: Zero + IndexMut<(usize, usize), Output = N> {
assert!(dim == 2 || dim == 3)... | cuboid_center_of_mass | 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/.
#![crate_type = "lib"]
#![crate_name = "tests"]
#![feature(custom_derive, type_ascription)]
macro_rules! test {
... | mod rc;
mod vec;
mod ringbuf;
mod hashmap;
mod iter;
mod str_two;
mod rmo;
mod str_three;
mod swap;
mod inotify;
mod env;
mod fs;
mod socket;
mod netlink;
mod sys;
mod poll;
mod dev;
mod file;
mod mqueue;
mod tty;
mod thread;
mod process;
mod time_ext;
mod dir;
mod user_group; | mod alloc;
mod queue;
// mod box;
mod c_ptr_ptr;
mod buf_reader; | random_line_split |
liveness-dead.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 | // option. This file may not be copied, modified, or distributed
// except according to those terms.
#![allow(dead_code)]
#![deny(dead_assignment)]
fn f1(x: &mut int) {
*x = 1; // no error
}
fn f2() {
let mut x: int = 3; //~ ERROR: value assigned to `x` is never read
x = 4;
x.clone();
}
fn f3() {
... | // 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 |
liveness-dead.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 ... | () {}
| main | identifier_name |
liveness-dead.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 main() {}
| {
let mut x: int = 3;
x.clone();
x = 4; //~ ERROR: value assigned to `x` is never read
} | identifier_body |
global.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/. */
//! Abstractions for global scopes.
//!
//! This module contains smart pointers to global scopes, to simplify writ... |
/// Get the `PipelineId` for this global scope.
pub fn pipeline(&self) -> PipelineId {
match *self {
GlobalRef::Window(window) => window.pipeline(),
GlobalRef::Worker(worker) => worker.pipeline(),
}
}
/// Get a `mem::ProfilerChan` to send messages to the memory... | {
match *self {
GlobalRef::Window(window) => window,
GlobalRef::Worker(_) => panic!("expected a Window scope"),
}
} | identifier_body |
global.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/. */
//! Abstractions for global scopes.
//!
//! This module contains smart pointers to global scopes, to simplify writ... | (&self, send_updates: bool) {
match *self {
GlobalRef::Window(window) => window.set_devtools_wants_updates(send_updates),
GlobalRef::Worker(worker) => worker.set_devtools_wants_updates(send_updates),
}
}
}
impl<'a> Reflectable for GlobalRef<'a> {
fn reflector<'b>(&'b sel... | set_devtools_wants_updates | identifier_name |
global.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/. */
//! Abstractions for global scopes.
//!
//! This module contains smart pointers to global scopes, to simplify writ... | pub fn get_cx(&self) -> *mut JSContext {
match *self {
GlobalRef::Window(ref window) => window.get_cx(),
GlobalRef::Worker(ref worker) => worker.get_cx(),
}
}
/// Extract a `Window`, causing task failure if the global object is not
/// a `Window`.
pub fn as_w... | }
impl<'a> GlobalRef<'a> {
/// Get the `JSContext` for the `JSRuntime` associated with the thread
/// this global object is on. | random_line_split |
pinky.rs | // This file is part of the uutils coreutils package.
//
// (c) Jian Zeng <anonymousknight96@gmail.com>
//
// For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code.
// spell-checker:ignore (ToDO) BUFSIZE gecos fullname, mesg iobuf
use uucore::entrie... | (&self, ut: &Utmpx) -> std::io::Result<()> {
let mut pts_path = PathBuf::from("/dev");
pts_path.push(ut.tty_device().as_str());
let mesg;
let last_change;
match pts_path.metadata() {
Ok(meta) => {
mesg = if meta.mode() & (S_IWGRP as u32)!= 0 {
... | print_entry | identifier_name |
pinky.rs | // This file is part of the uutils coreutils package.
//
// (c) Jian Zeng <anonymousknight96@gmail.com>
//
// For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code.
// spell-checker:ignore (ToDO) BUFSIZE gecos fullname, mesg iobuf
use uucore::entrie... |
}
println!();
} else {
println!("???");
}
}
}
}
fn read_to_console<F: Read>(f: F) {
let mut reader = BufReader::new(f);
let mut iobuf = [0_u8; BUFSIZE];
while let Ok(n) = reader.read(&mut iobuf) {
if n == 0 {
... | {
println!("Plan:");
read_to_console(f);
} | conditional_block |
pinky.rs | // This file is part of the uutils coreutils package.
//
// (c) Jian Zeng <anonymousknight96@gmail.com>
//
// For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code.
// spell-checker:ignore (ToDO) BUFSIZE gecos fullname, mesg iobuf
use uucore::entrie... | let include_heading =!matches.is_present(options::OMIT_HEADINGS);
// if true, display the user's full name from pw_gecos.
let mut include_fullname = true;
// if true, display the user's ~/.project file when doing long format.
let include_project =!matches.is_present(options::OMIT_PROJECT_FILE);
... | {
let args = args
.collect_str(InvalidEncodingHandling::Ignore)
.accept_any();
let after_help = get_long_usage();
let matches = uu_app().after_help(&after_help[..]).get_matches_from(args);
let users: Vec<String> = matches
.values_of(options::USER)
.map(|v| v.map(ToStri... | identifier_body |
pinky.rs | // This file is part of the uutils coreutils package.
//
// (c) Jian Zeng <anonymousknight96@gmail.com>
//
// For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code.
// spell-checker:ignore (ToDO) BUFSIZE gecos fullname, mesg iobuf
use uucore::entrie... | let mut pts_path = PathBuf::from("/dev");
pts_path.push(ut.tty_device().as_str());
let mesg;
let last_change;
match pts_path.metadata() {
Ok(meta) => {
mesg = if meta.mode() & (S_IWGRP as u32)!= 0 {
''
} else {
... | impl Pinky {
fn print_entry(&self, ut: &Utmpx) -> std::io::Result<()> { | random_line_split |
restyle_damage.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/. */
//! The restyle damage is a hint that tells layout which kind of operations may
//! be needed in presence of incre... |
write!(f, "{}", damage_str)?;
first_elem = false;
}
}
if first_elem {
write!(f, "NoDamage")?;
}
Ok(())
}
}
// NB: We need the braces inside the RHS due to Rust #8012. This particular
// version of this macro might be safe a... | { write!(f, " | ")?; } | conditional_block |
restyle_damage.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/. */
//! The restyle damage is a hint that tells layout which kind of operations may
//! be needed in presence of incre... | (self,
parent_is_absolutely_positioned: bool,
child_is_absolutely_positioned: bool)
-> ServoRestyleDamage {
match (parent_is_absolutely_positioned, child_is_absolutely_positioned) {
(false, true) => {
... | damage_for_child | identifier_name |
restyle_damage.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/. */
//! The restyle damage is a hint that tells layout which kind of operations may
//! be needed in presence of incre... |
/// Returns a bitmask indicating that the frame needs to be reconstructed.
pub fn reconstruct() -> ServoRestyleDamage {
RECONSTRUCT_FLOW
}
/// Supposing a flow has the given `position` property and this damage,
/// returns the damage that we should add to the *parent* of this flow.
pu... | {
REPAINT | REPOSITION | STORE_OVERFLOW | BUBBLE_ISIZES | REFLOW_OUT_OF_FLOW | REFLOW |
RECONSTRUCT_FLOW
} | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.