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 |
|---|---|---|---|---|
sdiv.rs | use num::Num;
#[inline]
pub fn sdiv<'a, 'b, T: Copy + Num>(out: &'a mut [T; 9], a: &'b [T; 9], s: T) -> &'a mut [T; 9] {
let not_zero = s!= T::zero();
out[0] = if not_zero {a[0] / s} else {T::zero()};
out[1] = if not_zero {a[1] / s} else {T::zero()};
out[2] = if not_zero {a[2] / s} else {T::zero()... | {
let mut v = [0, 0, 0, 0, 0, 0, 0, 0, 0];
sdiv(&mut v, &[1, 0, 0, 0, 1, 0, 0, 0, 1], 1);
assert!(v == [1, 0, 0, 0, 1, 0, 0, 0, 1]);
} | identifier_body | |
sdiv.rs | use num::Num;
#[inline]
pub fn sdiv<'a, 'b, T: Copy + Num>(out: &'a mut [T; 9], a: &'b [T; 9], s: T) -> &'a mut [T; 9] {
let not_zero = s!= T::zero();
out[0] = if not_zero {a[0] / s} else {T::zero()};
out[1] = if not_zero {a[1] / s} else {T::zero()};
out[2] = if not_zero {a[2] / s} else {T::zero()... | () {
let mut v = [0, 0, 0, 0, 0, 0, 0, 0, 0];
sdiv(&mut v, &[1, 0, 0, 0, 1, 0, 0, 0, 1], 1);
assert!(v == [1, 0, 0, 0, 1, 0, 0, 0, 1]);
}
| test_sdiv | identifier_name |
response.rs | // Copyright (c) 2016
// Jeff Nettleton
//
// Licensed under the MIT license (http://opensource.org/licenses/MIT). This
// file may not be copied, modified, or distributed except according to those
// terms
use std::collections::BTreeMap;
use chrono::Utc;
use serde_json;
use serde::Serialize;
const VERSION: &str = en... | (&mut self, ctype: &str) {
self.ctype = String::from(ctype);
}
/// Adds a header to the HTTP response.
///
/// # Examples
///
/// ```rust
/// use canteen::Response;
///
/// let mut res = Response::new();
/// res.add_header("Content-Type", "text/html");
/// ```
pu... | set_content_type | identifier_name |
response.rs | // Copyright (c) 2016
// Jeff Nettleton
//
// Licensed under the MIT license (http://opensource.org/licenses/MIT). This
// file may not be copied, modified, or distributed except according to those
// terms
use std::collections::BTreeMap;
use chrono::Utc;
use serde_json;
use serde::Serialize;
const VERSION: &str = en... |
/// Adds a header to the HTTP response.
///
/// # Examples
///
/// ```rust
/// use canteen::Response;
///
/// let mut res = Response::new();
/// res.add_header("Content-Type", "text/html");
/// ```
pub fn add_header(&mut self, key: &str, value: &str) {
if!self.heade... | {
self.ctype = String::from(ctype);
} | identifier_body |
response.rs | // Copyright (c) 2016
// Jeff Nettleton
//
// Licensed under the MIT license (http://opensource.org/licenses/MIT). This
// file may not be copied, modified, or distributed except according to those
// terms
use std::collections::BTreeMap;
use chrono::Utc;
use serde_json;
use serde::Serialize;
const VERSION: &str = en... | status: u16,
cmsg: String,
ctype: String,
headers: BTreeMap<String, String>,
payload: Vec<u8>,
}
impl Response {
/// Create a new, empty Response.
pub fn new() -> Response {
let mut res = Response {
status: 200,
cmsg: String::fr... | }
/// This struct reprsents the response to an HTTP client.
#[derive(Debug, Default)]
pub struct Response { | random_line_split |
lock.rs | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::fs;
use std::fs::File;
use std::io;
use std::path::Path;
use fs2::FileExt;
/// RAII lock on a filesystem path.
pub struct PathLock... | (&mut self) {
self.file.unlock().expect("unlock");
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::mpsc::channel;
use std::thread;
#[test]
fn test_path_lock() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let path = dir.path().join("a");
let (tx,... | drop | identifier_name |
lock.rs | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::fs;
use std::fs::File;
use std::io;
use std::path::Path;
use fs2::FileExt;
/// RAII lock on a filesystem path.
pub struct PathLock... | Ok(PathLock { file })
}
}
impl Drop for PathLock {
fn drop(&mut self) {
self.file.unlock().expect("unlock");
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::mpsc::channel;
use std::thread;
#[test]
fn test_path_lock() -> io::Result<()> {
let dir = temp... | file.lock_exclusive()?; | random_line_split |
check_static_recursion.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_util::is_local(def_id) => {
match self.ast_map.get(def_id.node) {
ast_map::NodeItem(item) =>
self.visit_item(item),
ast_map::NodeTraitItem(item) =>
self.vis... | Some(DefAssociatedConst(def_id, _)) |
Some(DefConst(def_id)) if | random_line_split |
check_static_recursion.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 ... | (v: &CheckCrateVisitor<'a, 'ast>, span: &'a Span)
-> CheckItemRecursionVisitor<'a, 'ast> {
CheckItemRecursionVisitor {
root_span: span,
sess: v.sess,
ast_map: v.ast_map,
def_map: v.def_map,
idstack: Vec::new()
}
}
fn with_ite... | new | identifier_name |
check_static_recursion.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 ... |
struct CheckItemRecursionVisitor<'a, 'ast: 'a> {
root_span: &'a Span,
sess: &'a Session,
ast_map: &'a ast_map::Map<'ast>,
def_map: &'a DefMap,
idstack: Vec<ast::NodeId>
}
impl<'a, 'ast: 'a> CheckItemRecursionVisitor<'a, 'ast> {
fn new(v: &CheckCrateVisitor<'a, 'ast>, span: &'a Span)
... | {
let mut visitor = CheckCrateVisitor {
sess: sess,
def_map: def_map,
ast_map: ast_map
};
visit::walk_crate(&mut visitor, krate);
sess.abort_if_errors();
} | identifier_body |
linux.rs | use crate::{error::{Error,
Result},
os::system::Uname};
use errno::errno;
use std::{ffi::CStr,
mem};
pub fn uname() -> Result<Uname> { unsafe { uname_libc() } }
unsafe fn uname_libc() -> Result<Uname> {
let mut utsname = mem::MaybeUninit::uninit();
let rv = libc::unam... | code, errno)));
}
Ok(Uname { sys_name: CStr::from_ptr(utsname.sysname.as_ptr()).to_string_lossy()
.into_owned(),
node_name: CStr::from_ptr(utsname.nodename.as_ptr()).to_string_lossy()
... | let code = errno.0 as i32;
return Err(Error::UnameFailed(format!("Error {} when calling uname: \
{}", | random_line_split |
linux.rs | use crate::{error::{Error,
Result},
os::system::Uname};
use errno::errno;
use std::{ffi::CStr,
mem};
pub fn uname() -> Result<Uname> { unsafe { uname_libc() } }
unsafe fn | () -> Result<Uname> {
let mut utsname = mem::MaybeUninit::uninit();
let rv = libc::uname(utsname.as_mut_ptr());
let utsname = utsname.assume_init();
if rv < 0 {
let errno = errno();
let code = errno.0 as i32;
return Err(Error::UnameFailed(format!("Error {} when calling uname: \
... | uname_libc | identifier_name |
linux.rs | use crate::{error::{Error,
Result},
os::system::Uname};
use errno::errno;
use std::{ffi::CStr,
mem};
pub fn uname() -> Result<Uname> |
unsafe fn uname_libc() -> Result<Uname> {
let mut utsname = mem::MaybeUninit::uninit();
let rv = libc::uname(utsname.as_mut_ptr());
let utsname = utsname.assume_init();
if rv < 0 {
let errno = errno();
let code = errno.0 as i32;
return Err(Error::UnameFailed(format!("Error {} ... | { unsafe { uname_libc() } } | identifier_body |
linux.rs | use crate::{error::{Error,
Result},
os::system::Uname};
use errno::errno;
use std::{ffi::CStr,
mem};
pub fn uname() -> Result<Uname> { unsafe { uname_libc() } }
unsafe fn uname_libc() -> Result<Uname> {
let mut utsname = mem::MaybeUninit::uninit();
let rv = libc::unam... |
Ok(Uname { sys_name: CStr::from_ptr(utsname.sysname.as_ptr()).to_string_lossy()
.into_owned(),
node_name: CStr::from_ptr(utsname.nodename.as_ptr()).to_string_lossy()
.i... | {
let errno = errno();
let code = errno.0 as i32;
return Err(Error::UnameFailed(format!("Error {} when calling uname: \
{}",
code, errno)));
} | conditional_block |
regex.rs | // Copyright 2015-2016 Joe Neeman.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except accordin... |
}
pub fn is_match(&self, s: &str) -> bool {
// TODO: for the forward-backward engine, this could be faster because we don't need
// to run backward.
self.find(s).is_some()
}
}
| {
None
} | conditional_block |
regex.rs | // Copyright 2015-2016 Joe Neeman.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except accordin... | Regex::new_bounded(re, std::usize::MAX)
}
/// Creates a new `Regex` from a regular expression string, but only if it doesn't require too
/// many states.
pub fn new_bounded(re: &str, max_states: usize) -> ::Result<Regex> {
let nfa = try!(Nfa::from_regex(re));
let nfa = nfa.remov... | pub fn new(re: &str) -> ::Result<Regex> { | random_line_split |
regex.rs | // Copyright 2015-2016 Joe Neeman.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except accordin... |
}
| {
// TODO: for the forward-backward engine, this could be faster because we don't need
// to run backward.
self.find(s).is_some()
} | identifier_body |
regex.rs | // Copyright 2015-2016 Joe Neeman.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except accordin... | (nfa: Nfa<u32, NoLooks>, max_states: usize)
-> ::Result<ForwardBackwardEngine<u8>> {
if nfa.is_anchored() {
return Err(Error::InvalidEngine("anchors rule out the forward-backward engine"));
}
let f_nfa = try!(try!(nfa.clone().byte_me(max_states)).anchor(max_states));
let... | make_forward_backward | identifier_name |
chip.rs | use common::{RingBuffer,Queue};
use ast;
//use adc;
use dma;
use nvic;
use usart;
use spi;
use gpio;
pub struct Sam4l;
const IQ_SIZE: usize = 100;
static mut IQ_BUF : [nvic::NvicIdx; IQ_SIZE] =
[nvic::NvicIdx::HFLASHC; IQ_SIZE];
pub static mut INTERRUPT_QUEUE : Option<RingBuffer<'static, nvic::NvicIdx>> = None;
... |
GPIO0 => gpio::PA.handle_interrupt(),
GPIO1 => gpio::PA.handle_interrupt(),
GPIO2 => gpio::PA.handle_interrupt(),
GPIO3 => gpio::PA.handle_interrupt(),
GPIO4 => gpio::PB.handle_interrupt(),
GPIO5 => gpio::PB.handle_interrup... | random_line_split | |
chip.rs | use common::{RingBuffer,Queue};
use ast;
//use adc;
use dma;
use nvic;
use usart;
use spi;
use gpio;
pub struct | ;
const IQ_SIZE: usize = 100;
static mut IQ_BUF : [nvic::NvicIdx; IQ_SIZE] =
[nvic::NvicIdx::HFLASHC; IQ_SIZE];
pub static mut INTERRUPT_QUEUE : Option<RingBuffer<'static, nvic::NvicIdx>> = None;
impl Sam4l {
#[inline(never)]
pub unsafe fn new() -> Sam4l {
INTERRUPT_QUEUE = Some(RingBuffer::new(&... | Sam4l | identifier_name |
exceptions.rs | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* 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 applic... | (&self) -> MessageType {
match self {
ResultType::Return | ResultType::Error => MessageType::Reply,
ResultType::Exception => MessageType::Exception,
}
}
}
| message_type | identifier_name |
exceptions.rs | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* 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 applic... | Return,
/// A declared exception
Error,
/// Some other exception (eg ApplicationException)
Exception,
}
impl ResultType {
pub fn message_type(&self) -> MessageType {
match self {
ResultType::Return | ResultType::Error => MessageType::Reply,
ResultType::Exception ... | #[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum ResultType {
/// A successful return | random_line_split |
cargo_compile.rs | Shell out to `--do get` for each source, and build up the list of paths
//! to pass to rustc -L
//! 5. Call `cargo-rustc` with the results of the resolver zipped together with
//! the results of the `get`
//!
//! a. Topologically sort the dependencies
//! b. Compile each dependency in order, passing in the... | ConfigValue::String(v, path) => {
if k == "rustc-flags" {
let whence = format!("in `{}` (in {})", key,
path.display());
let (paths, links) = try!(
BuildOutput::par... | let key = format!("{}.{}", key, lib_name);
let table = try!(config.get_table(&key)).unwrap().0;
for (k, _) in table.into_iter() {
let key = format!("{}.{}", key, k);
match try!(config.get(&key)).unwrap() { | random_line_split |
cargo_compile.rs | out to `--do get` for each source, and build up the list of paths
//! to pass to rustc -L
//! 5. Call `cargo-rustc` with the results of the resolver zipped together with
//! the results of the `get`
//!
//! a. Topologically sort the dependencies
//! b. Compile each dependency in order, passing in the -L's ... |
}
None => None,
};
let jobs = jobs.or(cfg_jobs).unwrap_or(::num_cpus::get() as u32);
let mut base = ops::BuildConfig {
jobs: jobs,
requested_target: target.clone(),
..Default::default()
};
base.host = try!(scrape_target_config(config, &config.rustc_info().host... | {
Some(n as u32)
} | conditional_block |
cargo_compile.rs | out to `--do get` for each source, and build up the list of paths
//! to pass to rustc -L
//! 5. Call `cargo-rustc` with the results of the resolver zipped together with
//! the results of the `get`
//!
//! a. Topologically sort the dependencies
//! b. Compile each dependency in order, passing in the -L's ... | <'a> {
Everything,
Only {
lib: bool,
bins: &'a [String],
examples: &'a [String],
tests: &'a [String],
benches: &'a [String],
}
}
pub fn compile<'a>(manifest_path: &Path,
options: &CompileOptions<'a>)
-> CargoResult<ops::Compilati... | CompileFilter | identifier_name |
cargo_compile.rs | out to `--do get` for each source, and build up the list of paths
//! to pass to rustc -L
//! 5. Call `cargo-rustc` with the results of the resolver zipped together with
//! the results of the `get`
//!
//! a. Topologically sort the dependencies
//! b. Compile each dependency in order, passing in the -L's ... | t.tested()
}).map(|t| {
(t, if t.is_example() {build} else {profile})
}).collect::<Vec<_>>();
// Always compile the library if we're testing everything as
// it'll be needed for doctests
... | {
let profiles = pkg.manifest().profiles();
let build = if release {&profiles.release} else {&profiles.dev};
let test = if release {&profiles.bench} else {&profiles.test};
let profile = match mode {
CompileMode::Test => test,
CompileMode::Bench => &profiles.bench,
CompileMode::Bu... | identifier_body |
difference.rs | use super::Style;
/// When printing out one coloured string followed by another, use one of
/// these rules to figure out which *extra* control codes need to be sent.
#[derive(PartialEq, Clone, Copy, Debug)]
pub enum Difference {
/// Print out the control codes specified by this style to end up looking
... |
if first.is_strikethrough &&!next.is_strikethrough {
return Reset;
}
// Cannot go from foreground to no foreground, so must Reset.
if first.foreground.is_some() && next.foreground.is_none() {
return Reset;
}
// Cannot go from backgro... | {
return Reset;
} | conditional_block |
difference.rs | use super::Style;
/// When printing out one coloured string followed by another, use one of
/// these rules to figure out which *extra* control codes need to be sent.
#[derive(PartialEq, Clone, Copy, Debug)]
pub enum Difference {
/// Print out the control codes specified by this style to end up looking
... | (first: &Style, next: &Style) -> Difference {
use self::Difference::*;
// XXX(Havvy): This algorithm is kind of hard to replicate without
// having the Plain/Foreground enum variants, so I'm just leaving
// it commented out for now, and defaulting to Reset.
if first == n... | between | identifier_name |
difference.rs | use super::Style;
/// When printing out one coloured string followed by another, use one of
/// these rules to figure out which *extra* control codes need to be sent.
#[derive(PartialEq, Clone, Copy, Debug)]
pub enum Difference {
/// Print out the control codes specified by this style to end up looking
... | if first.is_italic &&!next.is_italic {
return Reset;
}
// Cannot un-underline, so must Reset.
if first.is_underline &&!next.is_underline {
return Reset;
}
if first.is_blink &&!next.is_blink {
return Reset;
}
... | {
use self::Difference::*;
// XXX(Havvy): This algorithm is kind of hard to replicate without
// having the Plain/Foreground enum variants, so I'm just leaving
// it commented out for now, and defaulting to Reset.
if first == next {
return NoDifference;
... | identifier_body |
difference.rs | use super::Style;
/// When printing out one coloured string followed by another, use one of
/// these rules to figure out which *extra* control codes need to be sent.
#[derive(PartialEq, Clone, Copy, Debug)]
pub enum Difference {
/// Print out the control codes specified by this style to end up looking
... | use style::Colour::*;
use style::Style;
fn style() -> Style {
Style::new()
}
macro_rules! test {
($name: ident: $first: expr; $next: expr => $result: expr) => {
#[test]
fn $name() {
assert_eq!($result, Difference::between(&$first, ... | random_line_split | |
list_item.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/. */
//! Layout for elements with a CSS `display` property of `list-item`. These elements consist of a
//! block and an... |
fn bubble_inline_sizes(&mut self) {
// The marker contributes no intrinsic inline-size, so…
self.block_flow.bubble_inline_sizes()
}
fn assign_inline_sizes(&mut self, shared_context: &SharedStyleContext) {
self.block_flow.assign_inline_sizes(shared_context);
let mut marker... | {
&self.block_flow
} | identifier_body |
list_item.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/. */
//! Layout for elements with a CSS `display` property of `list-item`. These elements consist of a
//! block and an... | mut self, state: &mut DisplayListBuildState) {
self.build_display_list_for_list_item(state);
}
fn collect_stacking_contexts(&mut self,
parent_id: StackingContextId,
contexts: &mut Vec<Box<StackingContext>>)
... | ild_display_list(& | identifier_name |
list_item.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/. */
//! Layout for elements with a CSS `display` property of `list-item`. These elements consist of a
//! block and an... | let flow_size = self.block_flow.base.position.size.to_physical(self.block_flow.base.writing_mode);
let relative_containing_block_size =
&self.block_flow.base.early_absolute_position_info.relative_containing_block_size;
for fragment in &self.marker_fragments {
overflow.un... | }
fn compute_overflow(&self) -> Overflow {
let mut overflow = self.block_flow.compute_overflow(); | random_line_split |
error.rs | use std::error::Error as StdError;
use std::ffi::OsString;
use std::fmt;
use std::io::Error as IoError;
use std::io::ErrorKind as IoErrorKind;
use std::path::StripPrefixError;
/// A list specifying general categories of fs_extra error.
#[derive(Debug)]
pub enum ErrorKind {
/// An entity was not found.
NotFound... |
}
impl StdError for Error {
fn description(&self) -> &str {
self.kind.as_str()
}
}
impl From<StripPrefixError> for Error {
fn from(err: StripPrefixError) -> Error {
Error::new(
ErrorKind::StripPrefix(err),
"StripPrefixError. Look inside for more details",
)
... | {
write!(f, "{}", self.message)
} | identifier_body |
error.rs | use std::error::Error as StdError;
use std::ffi::OsString;
use std::fmt;
use std::io::Error as IoError;
use std::io::ErrorKind as IoErrorKind;
use std::path::StripPrefixError;
/// A list specifying general categories of fs_extra error.
#[derive(Debug)]
pub enum ErrorKind {
/// An entity was not found.
NotFound... | StripPrefix(StripPrefixError),
/// Any OsString error.
OsString(OsString),
/// Any fs_extra error not part of this list.
Other,
}
impl ErrorKind {
fn as_str(&self) -> &str {
match *self {
ErrorKind::NotFound => "entity not found",
ErrorKind::PermissionDenied => "... | random_line_split | |
error.rs | use std::error::Error as StdError;
use std::ffi::OsString;
use std::fmt;
use std::io::Error as IoError;
use std::io::ErrorKind as IoErrorKind;
use std::path::StripPrefixError;
/// A list specifying general categories of fs_extra error.
#[derive(Debug)]
pub enum ErrorKind {
/// An entity was not found.
NotFound... | (kind: ErrorKind, message: &str) -> Error {
Error {
kind,
message: message.to_string(),
}
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.message)
}
}
impl StdError for Error {
fn description(... | new | identifier_name |
build.rs | //! Generate a module with a custom `#[path=...]` for each of the files in our
//! libclang version-specific test expectations so that they get their layout
//! tests run. We need to do this because cargo doesn't automatically detect
//! tests subdirectories.
use std::env;
use std::fs;
use std::io::Write;
use std::pat... | }
println!("cargo:rerun-if-changed={}", path.display());
let module_name: String = path
.display()
.to_string()
.chars()
.map(|c| match c {
'a'..='z' | 'A'..='Z' | '0'..='9' => c,
_ ... | {
println!("cargo:rerun-if-changed=build.rs");
let mut test_string = String::new();
for dir in LIBCLANG_VERSION_DIRS {
let dir = Path::new(&env::var_os("CARGO_MANIFEST_DIR").unwrap())
.join("tests")
.join(dir);
println!("cargo:rerun-if-changed={}", dir.display());
... | identifier_body |
build.rs | //! Generate a module with a custom `#[path=...]` for each of the files in our
//! libclang version-specific test expectations so that they get their layout
//! tests run. We need to do this because cargo doesn't automatically detect
//! tests subdirectories.
use std::env;
use std::fs;
use std::io::Write;
use std::pat... |
test_string.push_str(&format!(
r###"
#[path = "{}"]
mod {};
"###,
path.display(),
module_name,
));
}
}
let out_path = Path::new(&env::var_os("OUT_DIR").unwrap())
.join("libclang_version_specific_generated_tests.rs");
le... | .collect(); | random_line_split |
build.rs | //! Generate a module with a custom `#[path=...]` for each of the files in our
//! libclang version-specific test expectations so that they get their layout
//! tests run. We need to do this because cargo doesn't automatically detect
//! tests subdirectories.
use std::env;
use std::fs;
use std::io::Write;
use std::pat... | () {
println!("cargo:rerun-if-changed=build.rs");
let mut test_string = String::new();
for dir in LIBCLANG_VERSION_DIRS {
let dir = Path::new(&env::var_os("CARGO_MANIFEST_DIR").unwrap())
.join("tests")
.join(dir);
println!("cargo:rerun-if-changed={}", dir.display());... | main | identifier_name |
glyph.rs | u32 = 0x0000FFFF;
fn is_simple_glyph_id(id: GlyphId) -> bool {
((id as u32) & GLYPH_ID_MASK) == id
}
fn is_simple_advance(advance: Au) -> bool {
advance >= Au(0) && {
let unsigned_au = advance.0 as u32;
(unsigned_au & (GLYPH_ADVANCE_MASK >> GLYPH_ADVANCE_SHIFT)) == unsigned_au
}
}... | self.advance_for_byte_range_slow_path(range, extra_word_spacing)
} | random_line_split | |
glyph.rs | _SPACE_SHIFT: u32 = 30;
const FLAG_IS_SIMPLE_GLYPH: u32 = 0x80000000;
// glyph advance; in Au's.
const GLYPH_ADVANCE_MASK: u32 = 0x3FFF0000;
const GLYPH_ADVANCE_SHIFT: u32 = 16;
const GLYPH_ID_MASK: u32 = 0x0000FFFF;
// Non-simple glyphs (more than one glyph per char; missing glyph,
// newli... | (&self, flag: u32) -> bool {
(self.value & flag)!= 0
}
}
// Stores data for a detailed glyph, in the case that several glyphs
// correspond to one character, or the glyph's data couldn't be packed.
#[derive(Clone, Debug, Copy, Deserialize, Serialize)]
struct DetailedGlyph {
id: GlyphId,
// glyph's ... | has_flag | identifier_name |
glyph.rs | _SPACE_SHIFT: u32 = 30;
const FLAG_IS_SIMPLE_GLYPH: u32 = 0x80000000;
// glyph advance; in Au's.
const GLYPH_ADVANCE_MASK: u32 = 0x3FFF0000;
const GLYPH_ADVANCE_SHIFT: u32 = 16;
const GLYPH_ID_MASK: u32 = 0x0000FFFF;
// Non-simple glyphs (more than one glyph per char; missing glyph,
// newli... | }
self.entry_buffer[i.to_usize()] = entry;
}
pub fn add_glyphs_for_byte_index(&mut self, i: ByteIndex, data_for_glyphs: &[GlyphData]) {
assert!(i < self.len());
assert!(data_for_glyphs.len() > 0);
let glyph_count = data_for_glyphs.len();
let first_glyph_data ... | {
let glyph_is_compressible = is_simple_glyph_id(data.id) &&
is_simple_advance(data.advance) &&
data.offset == Point2D::zero() &&
data.cluster_start; // others are stored in detail buffer
debug_assert!(data.ligature_start); // can't compress ligature continu... | identifier_body |
glyph.rs | _SPACE_SHIFT: u32 = 30;
const FLAG_IS_SIMPLE_GLYPH: u32 = 0x80000000;
// glyph advance; in Au's.
const GLYPH_ADVANCE_MASK: u32 = 0x3FFF0000;
const GLYPH_ADVANCE_SHIFT: u32 = 16;
const GLYPH_ID_MASK: u32 = 0x0000FFFF;
// Non-simple glyphs (more than one glyph per char; missing glyph,
// newli... |
});
let mut sorted_records = mut_records;
mem::swap(&mut self.detail_lookup, &mut sorted_records);
self.lookup_is_sorted = true;
}
}
// This struct is used by GlyphStore clients to provide new glyph data.
// It should be allocated on the stack and passed by reference to GlyphStore... | {
Ordering::Greater
} | conditional_block |
recolor.rs | use {RendTri, Shape, Color};
/// `Recolor` represents a shape which has had its color set to a new one.
#[derive(Copy, Clone, Debug)]
pub struct Recolor<S> {
shape: S,
color: Color,
}
impl<S> Recolor<S> {
pub(crate) fn new(shape: S, color: Color) -> Self |
}
impl<S> IntoIterator for Recolor<S>
where
S: Shape,
{
type Item = RendTri;
type IntoIter = RecolorIter<S::IntoIter>;
fn into_iter(self) -> Self::IntoIter {
RecolorIter {
iter: self.shape.into_iter(),
color: self.color,
}
}
}
/// Iterator which is produce... | {
Recolor {
shape: shape,
color: color,
}
} | identifier_body |
recolor.rs | use {RendTri, Shape, Color}; | shape: S,
color: Color,
}
impl<S> Recolor<S> {
pub(crate) fn new(shape: S, color: Color) -> Self {
Recolor {
shape: shape,
color: color,
}
}
}
impl<S> IntoIterator for Recolor<S>
where
S: Shape,
{
type Item = RendTri;
type IntoIter = RecolorIter<S::I... |
/// `Recolor` represents a shape which has had its color set to a new one.
#[derive(Copy, Clone, Debug)]
pub struct Recolor<S> { | random_line_split |
recolor.rs | use {RendTri, Shape, Color};
/// `Recolor` represents a shape which has had its color set to a new one.
#[derive(Copy, Clone, Debug)]
pub struct | <S> {
shape: S,
color: Color,
}
impl<S> Recolor<S> {
pub(crate) fn new(shape: S, color: Color) -> Self {
Recolor {
shape: shape,
color: color,
}
}
}
impl<S> IntoIterator for Recolor<S>
where
S: Shape,
{
type Item = RendTri;
type IntoIter = RecolorIte... | Recolor | identifier_name |
actor_system.rs | use threadpool::ThreadPool;
use actor::Role;
use actor_ref::ActorRef;
use std::collections::HashMap;
use std::cell::RefCell;
use std::rc::Rc;
use std::sync::Arc;
/// A central actor system which manages the actor references and actors
///
/// Spawns the actor system with a specified number of threads in the
/// cent... | (thread_count: usize) -> ActorSystem<'sys, 'b> {
ActorSystem {
pool: ThreadPool::new(thread_count),
actor_refs: Rc::new(RefCell::new(HashMap::<String, ActorRef<'sys, 'b>>::new())),
}
}
pub fn spawn_actor(&'sys self, name: String, role: Box<Role + Sync + Send +'static>) -... | new | identifier_name |
actor_system.rs | use threadpool::ThreadPool;
use actor::Role;
use actor_ref::ActorRef;
use std::collections::HashMap;
use std::cell::RefCell;
use std::rc::Rc;
use std::sync::Arc;
/// A central actor system which manages the actor references and actors
///
/// Spawns the actor system with a specified number of threads in the
/// cent... | // accessed by name. Depending on how actors are referenced this
// could be a more efficient way of referencing actors
pub pool: ThreadPool,
pub actor_refs: Rc<RefCell<HashMap<String, ActorRef<'sys, 'b>>>>
// pub actors: Rc<RefCell<HashMap<String, <Box<Role + Send +'static>>>>>
}
impl <'sys, 'b>A... | ///
pub struct ActorSystem<'sys, 'b: 'sys> {
// We can alternatively store actors in hashes so that they can be | random_line_split |
type-parameter-defaults-referencing-Self-ppaux.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 ... | (&self, other: &i32) -> i32 { *self + *other }
}
fn main() {
let x: i32 = 5;
let y = x as MyAdd<i32>;
//~^ ERROR as `MyAdd<i32>`
}
| add | identifier_name |
type-parameter-defaults-referencing-Self-ppaux.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 ... | {
let x: i32 = 5;
let y = x as MyAdd<i32>;
//~^ ERROR as `MyAdd<i32>`
} | identifier_body | |
type-parameter-defaults-referencing-Self-ppaux.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 MyAdd for i32 {
fn add(&self, other: &i32) -> i32 { *self + *other }
}
fn main() {
let x: i32 = 5;
let y = x as MyAdd<i32>;
//~^ ERROR as `MyAdd<i32>`
} | // the user, but pretty-printing the type during the error message
// caused an ICE.
trait MyAdd<Rhs=Self> { fn add(&self, other: &Rhs) -> Self; }
| random_line_split |
renderer.rs | extern crate raster;
use std::collections::LinkedList;
use std::cell::RefCell;
use std::rc::Rc;
use geometric::Geometric2D;
pub struct Renderer<'a> {
vertices: LinkedList<&'a Rc<RefCell<Box<Geometric2D>>>>,
image: raster::Image
} | Renderer {
vertices: LinkedList::new(),
image: raster::Image::blank(height, width)
}
}
pub fn save(self) {
self.save_as("test_tmp.png".to_owned());
}
pub fn add(&mut self, geo: &'a Rc<RefCell<Box<Geometric2D>>>) {
self.vertices.push_front(geo);
... |
impl<'a> Renderer<'a> {
//Construct a new Renderer
pub fn new(height: i32, width: i32) -> Renderer<'a> { | random_line_split |
renderer.rs | extern crate raster;
use std::collections::LinkedList;
use std::cell::RefCell;
use std::rc::Rc;
use geometric::Geometric2D;
pub struct Renderer<'a> {
vertices: LinkedList<&'a Rc<RefCell<Box<Geometric2D>>>>,
image: raster::Image
}
impl<'a> Renderer<'a> {
//Construct a new Renderer
pub fn new(height: i... |
pub fn save_as(&self, filename: String) {
raster::save(&self.image, &*filename);
}
pub fn draw_outline(&mut self) {
for v in &self.vertices {
v.borrow_mut().draw_outline(&mut self.image);
}
}
pub fn draw(&mut self) {
for v in &self.vertices {
... | {
self.vertices.push_front(geo);
} | identifier_body |
renderer.rs | extern crate raster;
use std::collections::LinkedList;
use std::cell::RefCell;
use std::rc::Rc;
use geometric::Geometric2D;
pub struct Renderer<'a> {
vertices: LinkedList<&'a Rc<RefCell<Box<Geometric2D>>>>,
image: raster::Image
}
impl<'a> Renderer<'a> {
//Construct a new Renderer
pub fn | (height: i32, width: i32) -> Renderer<'a> {
Renderer {
vertices: LinkedList::new(),
image: raster::Image::blank(height, width)
}
}
pub fn save(self) {
self.save_as("test_tmp.png".to_owned());
}
pub fn add(&mut self, geo: &'a Rc<RefCell<Box<Geometric2D>>>)... | new | identifier_name |
rparser.rs | //! common functions for all parsers
pub use crate::probe::{L3Info, L4Info, ProbeL4, ProbeResult};
use crate::Variant;
/// Direction of current packet in current stream
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum Direction {
/// Packet is sent from client to server
ToServer,
/// Packet is sent f... |
}
/// Interface of a parser builder
pub trait RBuilder: Send + Sync {
fn build(&self) -> Box<dyn RParser>;
fn get_l4_probe(&self) -> Option<ProbeL4> {
None
}
}
// status: return code, events
pub const R_STATUS_EVENTS: u32 = 0x0100;
pub const R_STATUS_OK: u32 = 0x0000;
pub const R_STATUS_FAIL: ... | {
[].iter()
} | identifier_body |
rparser.rs | //! common functions for all parsers
pub use crate::probe::{L3Info, L4Info, ProbeL4, ProbeResult};
use crate::Variant;
/// Direction of current packet in current stream
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum Direction {
/// Packet is sent from client to server
ToServer,
/// Packet is sent f... |
// Constants
pub const STREAM_TOSERVER: u8 = 0;
pub const STREAM_TOCLIENT: u8 = 1; | ($status & $crate::R_STATUS_EV_MASK) == $crate::R_STATUS_EVENTS
};
} | random_line_split |
rparser.rs | //! common functions for all parsers
pub use crate::probe::{L3Info, L4Info, ProbeL4, ProbeResult};
use crate::Variant;
/// Direction of current packet in current stream
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum | {
/// Packet is sent from client to server
ToServer,
/// Packet is sent from server to client
ToClient,
}
/// Return value from protocol probe trying to identify a protocol.
#[derive(Debug, Eq, PartialEq)]
pub enum ParseResult {
/// No error
///
/// Note that this does not mean that the pa... | Direction | identifier_name |
default.rs | use crate::deriving::generic::ty::*;
use crate::deriving::generic::*;
use rustc_ast::ptr::P;
use rustc_ast::walk_list;
use rustc_ast::EnumDef;
use rustc_ast::VariantData;
use rustc_ast::{Expr, MetaItem};
use rustc_errors::Applicability;
use rustc_expand::base::{Annotatable, DummyResult, ExtCtxt};
use rustc_span::symbo... | }
struct DetectNonVariantDefaultAttr<'a, 'b> {
cx: &'a ExtCtxt<'b>,
}
impl<'a, 'b> rustc_ast::visit::Visitor<'a> for DetectNonVariantDefaultAttr<'a, 'b> {
fn visit_attribute(&mut self, attr: &'a rustc_ast::Attribute) {
if attr.has_name(kw::Default) {
self.cx
.struct_span_err... | .emit();
return Err(());
}
Ok(()) | random_line_split |
default.rs | use crate::deriving::generic::ty::*;
use crate::deriving::generic::*;
use rustc_ast::ptr::P;
use rustc_ast::walk_list;
use rustc_ast::EnumDef;
use rustc_ast::VariantData;
use rustc_ast::{Expr, MetaItem};
use rustc_errors::Applicability;
use rustc_expand::base::{Annotatable, DummyResult, ExtCtxt};
use rustc_span::symbo... | }
}
}
fn default_enum_substructure(
cx: &mut ExtCtxt<'_>,
trait_span: Span,
enum_def: &EnumDef,
) -> P<Expr> {
let default_variant = match extract_default_variant(cx, enum_def, trait_span) {
Ok(value) => value,
Err(()) => return DummyResult::raw_expr(trait_span, true),
... | {
// Note that `kw::Default` is "default" and `sym::Default` is "Default"!
let default_ident = cx.std_path(&[kw::Default, sym::Default, kw::Default]);
let default_call = |span| cx.expr_call_global(span, default_ident.clone(), Vec::new());
match summary {
Unnamed(ref fields, is_tuple) => {
... | identifier_body |
default.rs | use crate::deriving::generic::ty::*;
use crate::deriving::generic::*;
use rustc_ast::ptr::P;
use rustc_ast::walk_list;
use rustc_ast::EnumDef;
use rustc_ast::VariantData;
use rustc_ast::{Expr, MetaItem};
use rustc_errors::Applicability;
use rustc_expand::base::{Annotatable, DummyResult, ExtCtxt};
use rustc_span::symbo... | (
cx: &mut ExtCtxt<'_>,
default_variant: &rustc_ast::Variant,
) -> Result<(), ()> {
let attrs: SmallVec<[_; 1]> =
cx.sess.filter_by_name(&default_variant.attrs, kw::Default).collect();
let attr = match attrs.as_slice() {
[attr] => attr,
[] => cx.bug(
"this method mus... | validate_default_attribute | identifier_name |
default.rs | use crate::deriving::generic::ty::*;
use crate::deriving::generic::*;
use rustc_ast::ptr::P;
use rustc_ast::walk_list;
use rustc_ast::EnumDef;
use rustc_ast::VariantData;
use rustc_ast::{Expr, MetaItem};
use rustc_errors::Applicability;
use rustc_expand::base::{Annotatable, DummyResult, ExtCtxt};
use rustc_span::symbo... |
Named(ref fields) => {
let default_fields = fields
.iter()
.map(|&(ident, span)| cx.field_imm(span, ident, default_call(span)))
.collect();
cx.expr_struct_ident(trait_span, substr.type_ident, default_fields)
}
}
}
fn default_enum... | {
if !is_tuple {
cx.expr_ident(trait_span, substr.type_ident)
} else {
let exprs = fields.iter().map(|sp| default_call(*sp)).collect();
cx.expr_call_ident(trait_span, substr.type_ident, exprs)
}
} | conditional_block |
filesystem.rs | use std::path::Path;
use std::fs::File;
use std::io::prelude::*;
use std::env;
pub fn check_extension(path: &Path, valid_ext: &[&str]) -> bool {
let ext = &path.extension().expect("The file has no extension").to_str().expect("Extension is not valid utf8");
for vext in valid_ext.iter() {
if vext == ext... | Err(msg) => panic!("Found non valid utf8 characters in {} : {}.", path.display(), msg)
}
},
Err(msg) => panic!("Error reading file {} : {}.", path.display(), msg)
}
} | {
let mut path = env::current_dir().unwrap();
path.push(Path::new(path_str));
if !path.exists() {
panic!("Error reading file, path {} doesn't exist.", path.display());
}
let mut f = match File::open(&path) {
Ok(f) => f,
Err(msg) => panic!("Error reading file {} : {}.",... | identifier_body |
filesystem.rs | use std::path::Path;
use std::fs::File;
use std::io::prelude::*;
use std::env;
pub fn check_extension(path: &Path, valid_ext: &[&str]) -> bool {
let ext = &path.extension().expect("The file has no extension").to_str().expect("Extension is not valid utf8");
for vext in valid_ext.iter() {
if vext == ext... |
let mut f = match File::open(&path) {
Ok(f) => f,
Err(msg) => panic!("Error reading file {} : {}.", path.display(), msg)
};
// read bytes and return as str
let mut bytes = Vec::new();
match f.read_to_end(&mut bytes) {
Ok(_) => {
match String::from_utf8(bytes) {... | {
panic!("Error reading file, path {} doesn't exist.", path.display());
} | conditional_block |
filesystem.rs | use std::path::Path;
use std::fs::File;
use std::io::prelude::*;
use std::env;
pub fn | (path: &Path, valid_ext: &[&str]) -> bool {
let ext = &path.extension().expect("The file has no extension").to_str().expect("Extension is not valid utf8");
for vext in valid_ext.iter() {
if vext == ext {
return true;
}
}
false
}
pub fn read_file(path_str: &str) -> String {
... | check_extension | identifier_name |
filesystem.rs | use std::path::Path;
use std::fs::File;
use std::io::prelude::*;
use std::env;
pub fn check_extension(path: &Path, valid_ext: &[&str]) -> bool {
let ext = &path.extension().expect("The file has no extension").to_str().expect("Extension is not valid utf8");
for vext in valid_ext.iter() {
if vext == ext... | } | },
Err(msg) => panic!("Error reading file {} : {}.", path.display(), msg)
} | random_line_split |
error.rs | // Copyright (c) 2016 Nikita Pekin and the smexybot contributors
// See the README.md file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/l... | (&self) -> Option<&StdError> {
use self::Error::*;
match *self {
Hyper(ref e) => e.cause(),
Io(ref e) => e.cause(),
Serde(ref e) => e.cause(),
UrlParse(ref e) => e.cause(),
}
}
}
impl From<hyper::Error> for Error {
fn from(error: hyper::E... | cause | identifier_name |
error.rs | // Copyright (c) 2016 Nikita Pekin and the smexybot contributors
// See the README.md file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/l... | Io(io::Error),
/// A `serde` crate error.
Serde(serde_json::Error),
/// Error while parsing a URL.
UrlParse(url::ParseError),
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
use self::Error::*;
match *self {
Hyper(ref e) => e.f... | /// A `hyper` crate error.
Hyper(hyper::Error),
/// An IO error was encountered. | random_line_split |
error.rs | // Copyright (c) 2016 Nikita Pekin and the smexybot contributors
// See the README.md file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/l... |
}
impl StdError for Error {
fn description(&self) -> &str {
use self::Error::*;
match *self {
Hyper(ref e) => e.description(),
Io(ref e) => e.description(),
Serde(ref e) => e.description(),
UrlParse(ref e) => e.description(),
}
}
fn... | {
use self::Error::*;
match *self {
Hyper(ref e) => e.fmt(f),
Io(ref e) => e.fmt(f),
Serde(ref e) => e.fmt(f),
UrlParse(ref e) => e.fmt(f),
}
} | identifier_body |
collision.rs |
use hlt::entity::{Entity, Position};
pub fn | <E: Entity, F: Entity, G: Entity>(start: &E, end: &F, circle: &G, fudge: f64) -> bool {
let Position(start_x, start_y) = start.get_position();
let Position(end_x, end_y) = end.get_position();
let Position(circle_x, circle_y) = circle.get_position();
let dx = end_x - start_x;
let dy = end_y - start_y... | intersect_segment_circle | identifier_name |
collision.rs |
use hlt::entity::{Entity, Position};
pub fn intersect_segment_circle<E: Entity, F: Entity, G: Entity>(start: &E, end: &F, circle: &G, fudge: f64) -> bool {
let Position(start_x, start_y) = start.get_position();
let Position(end_x, end_y) = end.get_position();
let Position(circle_x, circle_y) = circle.get_... |
let closest_x = start_x + dx * t;
let closest_y = start_y + dy * t;
let closest_distance = Position(closest_x, closest_y).calculate_distance_between(circle);
return closest_distance <= circle.get_radius() + fudge
}
| {
return false;
} | conditional_block |
collision.rs | let Position(end_x, end_y) = end.get_position();
let Position(circle_x, circle_y) = circle.get_position();
let dx = end_x - start_x;
let dy = end_y - start_y;
let a = dx.powi(2) + dy.powi(2);
let b = -2.0 * (start_x.powi(2) - start_x*end_x - start_x*circle_x + end_x*circle_x +
sta... | use hlt::entity::{Entity, Position};
pub fn intersect_segment_circle<E: Entity, F: Entity, G: Entity>(start: &E, end: &F, circle: &G, fudge: f64) -> bool {
let Position(start_x, start_y) = start.get_position(); | random_line_split | |
collision.rs |
use hlt::entity::{Entity, Position};
pub fn intersect_segment_circle<E: Entity, F: Entity, G: Entity>(start: &E, end: &F, circle: &G, fudge: f64) -> bool |
let closest_x = start_x + dx * t;
let closest_y = start_y + dy * t;
let closest_distance = Position(closest_x, closest_y).calculate_distance_between(circle);
return closest_distance <= circle.get_radius() + fudge
}
| {
let Position(start_x, start_y) = start.get_position();
let Position(end_x, end_y) = end.get_position();
let Position(circle_x, circle_y) = circle.get_position();
let dx = end_x - start_x;
let dy = end_y - start_y;
let a = dx.powi(2) + dy.powi(2);
let b = -2.0 * (start_x.powi(2) - start_x*... | identifier_body |
mod.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/. */
//! Generic types that share their serialization implementations
//! for both specified and computed values.
use ... |
}
impl ToCss for FontSettingTagFloat {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
dest.write_str(" ")?;
self.0.to_css(dest)
}
}
/// A wrapper of Non-negative values.
#[cfg_attr(feature = "servo", derive(Deserialize, HeapSizeOf, Serialize))]
#[derive(Animate, Clone,... | {
input.expect_number().map(FontSettingTagFloat).map_err(|e| e.into())
} | identifier_body |
mod.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/. */
//! Generic types that share their serialization implementations
//! for both specified and computed values.
use ... | if input.try(|i| i.expect_ident_matching("normal")).is_ok() {
return Ok(FontSettings::Normal);
}
Vec::parse(context, input).map(FontSettings::Tag)
}
}
/// An integer that can also parse "on" and "off",
/// for font-feature-settings
///
/// Do not use this type anywhere except wi... | random_line_split | |
mod.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/. */
//! Generic types that share their serialization implementations
//! for both specified and computed values.
use ... | <'i, 't>(_: &ParserContext, input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i>> {
input.expect_number().map(FontSettingTagFloat).map_err(|e| e.into())
}
}
impl ToCss for FontSettingTagFloat {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
dest.write_str(" ")?;
... | parse | identifier_name |
notestoreid.rs | //
// imag - the personal information management suite for the commandline
// Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the ... |
}
| {
self.is_in_collection(&["notes"])
} | identifier_body |
notestoreid.rs | //
// imag - the personal information management suite for the commandline
// Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the ... | (&self) -> bool {
self.is_in_collection(&["notes"])
}
}
| is_note_id | identifier_name |
notestoreid.rs | //
// imag - the personal information management suite for the commandline
// Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the ... | impl NoteStoreId for StoreId {
fn is_note_id(&self) -> bool {
self.is_in_collection(&["notes"])
}
} | pub trait NoteStoreId {
fn is_note_id(&self) -> bool;
}
| random_line_split |
text.rs | // #[cfg(all(test, has_display))]
// use crate::*;
// use crate::tests;
// use std::env;
// use std::path;
/* TODO; the font API has changed and I don't want to deal with it now
#[test]
fn test_calculated_text_width() {
let ctx = &mut make_context();
let font = graphics::Font::default();
let text = "Hell... | let width3 = font.width(text3);
let width4 = font.width(text4);
assert_eq!(width1, width2);
assert_eq!(width2, width3);
assert_eq!(width3, width4);
}
*/ |
let width1 = font.width(text1);
let width2 = font.width(text2); | random_line_split |
gaussian_mutation.rs | /// Performs gaussian mutation on solution parameters
///
/// Performs gaussian mutation on real-valued solution parameters,
/// currently hard-coded for 30 problem variables for the ZDT1
/// synthetic test function.
extern crate rand;
use rand::{random, thread_rng, Rng};
// bounds hard-coded for ZDT1 i.e. (0,1)
pub f... | {
let std = 1_f32 - 0_f32 / 10_f32;
for parameter in &mut parameters[..] {
if random::<f32>() <= mutation_rate {
let mutation = thread_rng().gen_range(-1.0f32, 1.0f32) * std;
*parameter = *parameter + mutation;
// Enforce bounds
*parameter = f32::max(*par... | identifier_body | |
gaussian_mutation.rs | /// Performs gaussian mutation on solution parameters
///
/// Performs gaussian mutation on real-valued solution parameters,
/// currently hard-coded for 30 problem variables for the ZDT1
/// synthetic test function.
extern crate rand;
use rand::{random, thread_rng, Rng};
// bounds hard-coded for ZDT1 i.e. (0,1)
pub f... | (mut parameters: [f32; 30], mutation_rate: f32) -> [f32; 30] {
let std = 1_f32 - 0_f32 / 10_f32;
for parameter in &mut parameters[..] {
if random::<f32>() <= mutation_rate {
let mutation = thread_rng().gen_range(-1.0f32, 1.0f32) * std;
*parameter = *parameter + mutation;
... | gaussian_mutation | identifier_name |
gaussian_mutation.rs | /// Performs gaussian mutation on solution parameters
///
/// Performs gaussian mutation on real-valued solution parameters,
/// currently hard-coded for 30 problem variables for the ZDT1
/// synthetic test function.
extern crate rand;
use rand::{random, thread_rng, Rng};
// bounds hard-coded for ZDT1 i.e. (0,1)
pub f... | return parameters;
} | *parameter = f32::min(*parameter, 1_f32);
}
} | random_line_split |
gaussian_mutation.rs | /// Performs gaussian mutation on solution parameters
///
/// Performs gaussian mutation on real-valued solution parameters,
/// currently hard-coded for 30 problem variables for the ZDT1
/// synthetic test function.
extern crate rand;
use rand::{random, thread_rng, Rng};
// bounds hard-coded for ZDT1 i.e. (0,1)
pub f... |
}
return parameters;
}
| {
let mutation = thread_rng().gen_range(-1.0f32, 1.0f32) * std;
*parameter = *parameter + mutation;
// Enforce bounds
*parameter = f32::max(*parameter, 0_f32);
*parameter = f32::min(*parameter, 1_f32);
} | conditional_block |
privacy-ns1.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 ... | ;
pub fn Bar() { }
}
fn test_glob2() {
use foo2::*;
let _x: Box<Bar>; //~ ERROR use of undeclared type name `Bar`
}
// neither public
pub mod foo3 {
trait Bar {
}
pub struct Baz;
fn Bar() { }
}
fn test_glob3() {
use foo3::*;
Bar(); //~ ERROR unresolved name `Bar`
let _x:... | Baz | identifier_name |
privacy-ns1.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 ... |
}
fn test_glob2() {
use foo2::*;
let _x: Box<Bar>; //~ ERROR use of undeclared type name `Bar`
}
// neither public
pub mod foo3 {
trait Bar {
}
pub struct Baz;
fn Bar() { }
}
fn test_glob3() {
use foo3::*;
Bar(); //~ ERROR unresolved name `Bar`
let _x: Box<Bar>; //~ ERROR ... | { } | identifier_body |
privacy-ns1.rs | // http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except accordin... | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at | random_line_split | |
text.rs | ::with_capacity(run_info_list.len());
for run_info in run_info_list {
let mut options = options;
options.script = run_info.script;
if run_info.bidi_level.is_rtl() {
options.flags.insert(ShapingFlags::RTL_FLAG);
}
... | a == b || !is_specific(a) || !is_specific(b)
}
/ | identifier_body | |
text.rs | InlineFragments {
fragments: new_fragments,
}
}
/// A "clump" is a range of inline flow leaves that can be merged together into a single
/// fragment. Adjacent text with the same style can be merged, and nothing else can.
///
/// The flow keeps track of the fragments contained ... | (&mut self,
font_context: &mut FontContext,
out_fragments: &mut Vec<Fragment>,
paragraph_bytes_processed: &mut usize,
bidi_levels: Option<&[bidi::Level]>,
mut last_whitespace: bool,
... | flush_clump_to_list | identifier_name |
text.rs | };
// Now, if necessary, flush the mapping we were building up.
let flush_run = run_info.font_index!= font_index ||
run_info.bidi_level!= bidi_level ||
!compatible_script;
... | old_fragment_index: fragment_index, | random_line_split | |
input.rs | #![allow(unused_variables)]
/// Motion directions
pub enum Direction {
North,
NorthEast,
East,
SouthEast,
South,
SouthWest,
West,
NorthWest,
}
/// Commands
///
/// They can be generated by a user input, or as the consequences of
/// some other actions.
pub enum Command {
// List of... | (&self, key: char) {
unimplemented!();
}
}
| process_help | identifier_name |
input.rs | #![allow(unused_variables)]
/// Motion directions
pub enum Direction {
North,
NorthEast,
East,
SouthEast,
South,
SouthWest,
West,
NorthWest,
}
/// Commands
///
/// They can be generated by a user input, or as the consequences of
/// some other actions.
pub enum Command {
// List of... | self.mode = new_mode;
}
pub fn process_key(&self, key: char) {
match self.mode {
InputMode::Normal => self.process_normal(key),
InputMode::Explore => self.process_explore(key),
InputMode::Menu => self.process_menu(key),
InputMode::YesOrNo => self.... | random_line_split | |
input.rs | #![allow(unused_variables)]
/// Motion directions
pub enum Direction {
North,
NorthEast,
East,
SouthEast,
South,
SouthWest,
West,
NorthWest,
}
/// Commands
///
/// They can be generated by a user input, or as the consequences of
/// some other actions.
pub enum Command {
// List of... |
fn process_menu(&self, key: char) {
unimplemented!();
}
fn process_yesorno(&self, key: char) {
unimplemented!();
}
fn process_help(&self, key: char) {
unimplemented!();
}
}
| {
unimplemented!();
} | identifier_body |
mailbox.rs | // Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0.
use crate::fsm::{Fsm, FsmScheduler, FsmState};
use crossbeam::channel::{SendError, TrySendError};
use std::borrow::Cow;
use std::sync::Arc;
use tikv_util::mpsc;
/// A basic mailbox.
///
/// Every mailbox should have one and only one owner, who will re... | (&self) -> BasicMailbox<Owner> {
BasicMailbox {
sender: self.sender.clone(),
state: self.state.clone(),
}
}
}
/// A more high level mailbox.
pub struct Mailbox<Owner, Scheduler>
where
Owner: Fsm,
Scheduler: FsmScheduler<Fsm = Owner>,
{
mailbox: BasicMailbox<Owner... | clone | identifier_name |
mailbox.rs | // Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0.
use crate::fsm::{Fsm, FsmScheduler, FsmState};
use crossbeam::channel::{SendError, TrySendError};
use std::borrow::Cow;
use std::sync::Arc;
use tikv_util::mpsc;
/// A basic mailbox.
///
/// Every mailbox should have one and only one owner, who will re... |
pub(crate) fn release(&self, fsm: Box<Owner>) {
self.state.release(fsm)
}
pub(crate) fn take_fsm(&self) -> Option<Box<Owner>> {
self.state.take_fsm()
}
#[inline]
pub fn len(&self) -> usize {
self.sender.len()
}
#[inline]
pub fn is_empty(&self) -> bool {
... | {
self.sender.is_sender_connected()
} | identifier_body |
mailbox.rs | // Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0.
use crate::fsm::{Fsm, FsmScheduler, FsmState};
use crossbeam::channel::{SendError, TrySendError};
use std::borrow::Cow;
use std::sync::Arc;
use tikv_util::mpsc;
/// A basic mailbox.
///
/// Every mailbox should have one and only one owner, who will re... | #[inline]
pub fn force_send(&self, msg: Owner::Message) -> Result<(), SendError<Owner::Message>> {
self.mailbox.force_send(msg, &self.scheduler)
}
/// Try to send a message.
#[inline]
pub fn try_send(&self, msg: Owner::Message) -> Result<(), TrySendError<Owner::Message>> {
self.... | pub fn new(mailbox: BasicMailbox<Owner>, scheduler: Scheduler) -> Mailbox<Owner, Scheduler> {
Mailbox { mailbox, scheduler }
}
/// Force sending a message despite channel capacity limit. | random_line_split |
gdal_ds.rs | //
// Copyright (c) Pirmin Kalberer. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
//
use crate::gdal_fields::*;
use gdal::spatial_ref::{CoordTransform, SpatialRef};
use gdal::vector::Geometry;
use gdal::Dataset;
use std::collections::BTreeMa... | (&self, layer: &Layer, grid_srid: i32) -> Option<Extent> {
let dataset = Dataset::open(Path::new(&self.path)).unwrap();
let layer_name = layer.table_name.as_ref().unwrap();
let ogr_layer = dataset.layer_by_name(layer_name).unwrap();
let extent = match ogr_layer.get_extent() {
... | layer_extent | identifier_name |
gdal_ds.rs | //
// Copyright (c) Pirmin Kalberer. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
//
use crate::gdal_fields::*;
use gdal::spatial_ref::{CoordTransform, SpatialRef};
use gdal::vector::Geometry;
use gdal::Dataset;
use std::collections::BTreeMa... |
impl<'a> Config<'a, DatasourceCfg> for GdalDatasource {
fn from_config(ds_cfg: &DatasourceCfg) -> Result<Self, String> {
Ok(GdalDatasource::new(ds_cfg.path.as_ref().unwrap()))
}
fn gen_config() -> String {
let toml = r#"
[[datasource]]
name = "ds"
# Dataset specification (http://gdal.org/... | {
let xs = &mut [extent.minx, extent.maxx];
let ys = &mut [extent.miny, extent.maxy];
transformation.transform_coords(xs, ys, &mut [0.0, 0.0])?;
Ok(Extent {
minx: *xs.get(0).unwrap(),
miny: *ys.get(0).unwrap(),
maxx: *xs.get(1).unwrap(),
maxy: *ys.get(1).unwrap(),
})
... | identifier_body |
gdal_ds.rs | //
// Copyright (c) Pirmin Kalberer. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
//
use crate::gdal_fields::*;
use gdal::spatial_ref::{CoordTransform, SpatialRef};
use gdal::vector::Geometry;
use gdal::Dataset;
use std::collections::BTreeMa... | }
if layer.simplify {
if layer.geometry_type!= Some("POINT".to_string()) {
warn!(
"Layer '{}': Simplification not supported for GDAL layers",
layer.name
);
}
}
if layer.buffer_size.is_some() ... | }
} else {
warn!("Layer '{}': Couldn't detect spatialref", layer.name);
} | random_line_split |
gdal_ds.rs | //
// Copyright (c) Pirmin Kalberer. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
//
use crate::gdal_fields::*;
use gdal::spatial_ref::{CoordTransform, SpatialRef};
use gdal::vector::Geometry;
use gdal::Dataset;
use std::collections::BTreeMa... |
}
if layer.simplify {
if layer.geometry_type!= Some("POINT".to_string()) {
warn!(
"Layer '{}': Simplification not supported for GDAL layers",
layer.name
);
}
}
if layer.buffer_size.is_some()... | {
warn!("Layer '{}': Couldn't detect spatialref", layer.name);
} | conditional_block |
enum-headings.rs | #![crate_name = "foo"]
// @has foo/enum.Token.html
/// A token!
/// # First
/// Some following text... | // @has - '//h4[@id="variant-first"]' "Variant-First"
Declaration {
/// A version!
/// # Variant-Field-First
/// Some following text...
// @has - '//h5[@id="variant-field-first"]' "Variant-Field-First"
version: String,
},
/// A Zoople!
/// # Variant-First
... | // @has - '//h2[@id="first"]' "First"
pub enum Token {
/// A declaration!
/// # Variant-First
/// Some following text... | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.