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
textencoder.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::TextEncoderBinding; use dom::bindings::codegen::Bindings::TextEncoderBinding...
encoder: encoder, } } pub fn new(global: GlobalRef, encoding: DOMString, encoder: EncodingRef) -> Temporary<TextEncoder> { reflect_dom_object(box TextEncoder::new_inherited(encoding, encoder), global, TextEncoderBinding::Wrap) ...
encoding: encoding,
random_line_split
textencoder.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::TextEncoderBinding; use dom::bindings::codegen::Bindings::TextEncoderBinding...
}
{ unsafe { let output = self.encoder.encode(&input.0, EncoderTrap::Strict).unwrap(); let length = output.len() as u32; let js_object: *mut JSObject = JS_NewUint8Array(cx, length); let js_object_data: *mut uint8_t = JS_GetUint8ArrayData(js_object, cx); ...
identifier_body
textencoder.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::TextEncoderBinding; use dom::bindings::codegen::Bindings::TextEncoderBinding...
(global: GlobalRef, encoding: DOMString, encoder: EncodingRef) -> Temporary<TextEncoder> { reflect_dom_object(box TextEncoder::new_inherited(encoding, encoder), global, TextEncoderBinding::Wrap) } // https://encoding.spec.whatwg.org/#dom-textencoder...
new
identifier_name
mir_overflow_off.rs
// Copyright 2016 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 ...
() { assert_eq!(i8::neg(-0x80), -0x80); assert_eq!(u8::add(0xff, 1), 0_u8); assert_eq!(u8::sub(0, 1), 0xff_u8); assert_eq!(u8::mul(0xff, 2), 0xfe_u8); assert_eq!(u8::shl(1, 9), 2_u8); assert_eq!(u8::shr(2, 9), 1_u8); }
main
identifier_name
mir_overflow_off.rs
// // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // run-pass // c...
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT.
random_line_split
mir_overflow_off.rs
// Copyright 2016 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 ...
{ assert_eq!(i8::neg(-0x80), -0x80); assert_eq!(u8::add(0xff, 1), 0_u8); assert_eq!(u8::sub(0, 1), 0xff_u8); assert_eq!(u8::mul(0xff, 2), 0xfe_u8); assert_eq!(u8::shl(1, 9), 2_u8); assert_eq!(u8::shr(2, 9), 1_u8); }
identifier_body
ffi.rs
//! FFI functions, only to be called from C. //! //! Equivalent C versions of these live in `src/common/compat_rust.c` use std::mem::forget; use std::ffi::CString; use libc; use rust_string::RustString; /// Free the passed `RustString` (`rust_str_t` in C), to be used in place of /// `tor_free`(). /// /// # Examples ...
/// Returns a short string to announce Rust support during startup. /// /// # Examples /// ```c /// rust_str_t r_s = rust_welcome_string(); /// const char *s = rust_str_get(r_s); /// printf("%s", s); /// rust_str_free(r_s); /// ``` #[no_mangle] pub extern "C" fn rust_welcome_string() -> RustString { let s = CStri...
{ let res = str.as_ptr(); forget(str); res }
identifier_body
ffi.rs
//! FFI functions, only to be called from C. //! //! Equivalent C versions of these live in `src/common/compat_rust.c` use std::mem::forget; use std::ffi::CString; use libc; use rust_string::RustString; /// Free the passed `RustString` (`rust_str_t` in C), to be used in place of /// `tor_free`(). /// /// # Examples ...
(_str: RustString) { // Empty body: Just drop _str and we're done (Drop takes care of it). } /// Lends an immutable, NUL-terminated C String. /// /// # Examples /// ```c /// rust_str_t r_s = rust_welcome_string(); /// const char *s = rust_str_get(r_s); /// printf("%s", s); /// rust_str_free(r_s); /// ``` #[no_mang...
rust_str_free
identifier_name
ffi.rs
//! FFI functions, only to be called from C. //! //! Equivalent C versions of these live in `src/common/compat_rust.c` use std::mem::forget; use std::ffi::CString; use libc; use rust_string::RustString; /// Free the passed `RustString` (`rust_str_t` in C), to be used in place of /// `tor_free`(). /// /// # Examples ...
/// Lends an immutable, NUL-terminated C String. /// /// # Examples /// ```c /// rust_str_t r_s = rust_welcome_string(); /// const char *s = rust_str_get(r_s); /// printf("%s", s); /// rust_str_free(r_s); /// ``` #[no_mangle] pub unsafe extern "C" fn rust_str_get(str: RustString) -> *const libc::c_char { let res = ...
}
random_line_split
document_attributes.rs
use azure_sdk_core::errors::AzureError; use azure_sdk_core::prelude::IfMatchCondition; use http::HeaderMap; #[derive(Default, Serialize, Deserialize, Debug, Clone, PartialEq)] pub struct DocumentAttributes { #[serde(rename = "_rid")] pub rid: String, #[serde(rename = "_ts")] pub ts: u64, #[serde(re...
} impl std::convert::TryFrom<(&HeaderMap, &[u8])> for DocumentAttributes { type Error = AzureError; fn try_from(value: (&HeaderMap, &[u8])) -> Result<Self, Self::Error> { let body = value.1; Ok(serde_json::from_slice(body)?) } } impl<'a> std::convert::From<&'a DocumentAttributes> for IfMa...
{ self.attachments = value.into(); }
identifier_body
document_attributes.rs
use azure_sdk_core::errors::AzureError; use azure_sdk_core::prelude::IfMatchCondition; use http::HeaderMap; #[derive(Default, Serialize, Deserialize, Debug, Clone, PartialEq)] pub struct DocumentAttributes { #[serde(rename = "_rid")] pub rid: String, #[serde(rename = "_ts")] pub ts: u64, #[serde(re...
(&mut self, value: u64) { self.ts = value; } pub fn set_self<T>(&mut self, value: T) where T: Into<String>, { self._self = value.into(); } pub fn set_etag<T>(&mut self, value: T) where T: Into<String>, { self.etag = value.into(); } pub f...
set_ts
identifier_name
document_attributes.rs
use azure_sdk_core::errors::AzureError; use azure_sdk_core::prelude::IfMatchCondition; use http::HeaderMap; #[derive(Default, Serialize, Deserialize, Debug, Clone, PartialEq)] pub struct DocumentAttributes { #[serde(rename = "_rid")] pub rid: String, #[serde(rename = "_ts")] pub ts: u64, #[serde(re...
attachments: "attachments".to_owned(), }; a.set_attachments("new_attachments".to_owned()); } }
etag: "etag".to_owned(),
random_line_split
lib.rs
// Copyright 2018 TiKV Project Authors. Licensed under Apache-2.0. #![feature(test)] extern crate test; #[macro_use] extern crate slog_global; pub mod encryption; mod kv_generator; mod logging; mod macros; mod runner; mod security; use rand::Rng; use std::sync::atomic::{AtomicU16, Ordering}; use std::{env, thread};...
if env::var("LOG_FILE").is_ok() { logging::init_log_for_test(); } } if env::var("PANIC_ABORT").is_ok() { // Panics as aborts, it's helpful for debugging, // but also stops tests immediately. tikv_util::set_panic_hook(true, "./"); } tikv_util::check_...
{ // We use backtrace in tests to record suspicious problems. And loading backtrace // the first time can take several seconds. Spawning a thread and load it ahead // of time to avoid causing timeout. thread::Builder::new() .name(tikv_util::thd_name!("backtrace-loader")) .spawn(::backtra...
identifier_body
lib.rs
// Copyright 2018 TiKV Project Authors. Licensed under Apache-2.0. #![feature(test)] extern crate test; #[macro_use] extern crate slog_global; pub mod encryption; mod kv_generator; mod logging; mod macros; mod runner; mod security; use rand::Rng; use std::sync::atomic::{AtomicU16, Ordering}; use std::{env, thread};...
() { // We use backtrace in tests to record suspicious problems. And loading backtrace // the first time can take several seconds. Spawning a thread and load it ahead // of time to avoid causing timeout. thread::Builder::new() .name(tikv_util::thd_name!("backtrace-loader")) .spawn(::backtr...
setup_for_ci
identifier_name
lib.rs
// Copyright 2018 TiKV Project Authors. Licensed under Apache-2.0. #![feature(test)]
#[macro_use] extern crate slog_global; pub mod encryption; mod kv_generator; mod logging; mod macros; mod runner; mod security; use rand::Rng; use std::sync::atomic::{AtomicU16, Ordering}; use std::{env, thread}; pub use crate::encryption::*; pub use crate::kv_generator::*; pub use crate::logging::*; pub use crate::...
extern crate test;
random_line_split
to_bytes.rs
use bytes::{Buf, BufMut, Bytes}; use super::HttpBody; /// Concatenate the buffers from a body into a single `Bytes` asynchronously. /// /// This may require copying the data into a single buffer. If you don't need /// a contiguous buffer, prefer the [`aggregate`](crate::body::aggregate()) /// function. /// /// # Note...
vec.put(second); while let Some(buf) = body.data().await { vec.put(buf?); } Ok(vec.into()) }
{ futures_util::pin_mut!(body); // If there's only 1 chunk, we can just return Buf::to_bytes() let mut first = if let Some(buf) = body.data().await { buf? } else { return Ok(Bytes::new()); }; let second = if let Some(buf) = body.data().await { buf? } else { ...
identifier_body
to_bytes.rs
use bytes::{Buf, BufMut, Bytes}; use super::HttpBody; /// Concatenate the buffers from a body into a single `Bytes` asynchronously. /// /// This may require copying the data into a single buffer. If you don't need /// a contiguous buffer, prefer the [`aggregate`](crate::body::aggregate()) /// function. /// /// # Note...
/// let body_bytes = hyper::body::to_bytes(response.into_body()).await?; /// println!("body: {:?}", body_bytes); /// } /// /// # Ok(()) /// # } /// ``` pub async fn to_bytes<T>(body: T) -> Result<Bytes, T::Error> where T: HttpBody, { futures_util::pin_mut!(body); // If there's only 1 chunk, we can ...
/// /// if response_content_length < MAX_ALLOWED_RESPONSE_SIZE {
random_line_split
to_bytes.rs
use bytes::{Buf, BufMut, Bytes}; use super::HttpBody; /// Concatenate the buffers from a body into a single `Bytes` asynchronously. /// /// This may require copying the data into a single buffer. If you don't need /// a contiguous buffer, prefer the [`aggregate`](crate::body::aggregate()) /// function. /// /// # Note...
else { return Ok(Bytes::new()); }; let second = if let Some(buf) = body.data().await { buf? } else { return Ok(first.copy_to_bytes(first.remaining())); }; // With more than 1 buf, we gotta flatten into a Vec first. let cap = first.remaining() + second.remaining() + bod...
{ buf? }
conditional_block
to_bytes.rs
use bytes::{Buf, BufMut, Bytes}; use super::HttpBody; /// Concatenate the buffers from a body into a single `Bytes` asynchronously. /// /// This may require copying the data into a single buffer. If you don't need /// a contiguous buffer, prefer the [`aggregate`](crate::body::aggregate()) /// function. /// /// # Note...
<T>(body: T) -> Result<Bytes, T::Error> where T: HttpBody, { futures_util::pin_mut!(body); // If there's only 1 chunk, we can just return Buf::to_bytes() let mut first = if let Some(buf) = body.data().await { buf? } else { return Ok(Bytes::new()); }; let second = if let Som...
to_bytes
identifier_name
main.rs
#![feature(associated_consts,collections,custom_derive,ip,lookup_host,optin_builtin_traits,plugin,repr_simd,slice_patterns)] #![allow(dead_code)] #![plugin(docopt_macros)] #![plugin(rand_macros)] #![plugin(serde_macros)] extern crate bincode; extern crate byte_conv; extern crate collections; extern crate core; extern ...
if let hash_map::Entry::Vacant(entry) = self.key_down.entry(key){ entry.insert(mapping.repeat_delay); request_sender.send(Request::PlayerInput{input: mapping.input,player: mapping.player}).unwrap(); } } }} } fn on_key_release(&mut self,key: Key){ if let hash_map::Entry::Occupied(entry) = sel...
}, Key::Home => {if let Some(player) = self.game_state.data.players.get_mut(0 as usize){player.pos.y = 0;};}, //Other keys, check key bindings key => if let Some(mapping) = self.key_map.get(&key){
random_line_split
main.rs
#![feature(associated_consts,collections,custom_derive,ip,lookup_host,optin_builtin_traits,plugin,repr_simd,slice_patterns)] #![allow(dead_code)] #![plugin(docopt_macros)] #![plugin(rand_macros)] #![plugin(serde_macros)] extern crate bincode; extern crate byte_conv; extern crate collections; extern crate core; extern ...
} } //Input while let Ok(request) = self.request_receiver.try_recv(){match request{ Request::PlayerInput{input,player: pid} => { if let Some(player) = self.game_state.data.players.get_mut(pid as usize){ if let Some(&mut(ref mut world,false)) = self.game_state.data.worlds.get_mut(player.world as u...
{ f64::NAN//TODO: If the mapping doesn't exist, it will never be removed }
conditional_block
main.rs
#![feature(associated_consts,collections,custom_derive,ip,lookup_host,optin_builtin_traits,plugin,repr_simd,slice_patterns)] #![allow(dead_code)] #![plugin(docopt_macros)] #![plugin(rand_macros)] #![plugin(serde_macros)] extern crate bincode; extern crate byte_conv; extern crate collections; extern crate core; extern ...
{ gl: GlGraphics, game_state: game::State<World<cell::ShapeCell>,rand::StdRng>, controllers: Vec<Box<Controller<World<cell::ShapeCell>,Event<(PlayerId,WorldId),WorldId>>>>, request_receiver: sync::mpsc::Receiver<Request<PlayerId,WorldId>>, connection: online::ConnectionType, paused: bool, key_map: ::game::data::...
App
identifier_name
main.rs
#![feature(associated_consts,collections,custom_derive,ip,lookup_host,optin_builtin_traits,plugin,repr_simd,slice_patterns)] #![allow(dead_code)] #![plugin(docopt_macros)] #![plugin(rand_macros)] #![plugin(serde_macros)] extern crate bincode; extern crate byte_conv; extern crate collections; extern crate core; extern ...
} } //Input while let Ok(request) = self.request_receiver.try_recv(){match request{ Request::PlayerInput{input,player: pid} => { if let Some(player) = self.game_state.data.players.get_mut(pid as usize){ if let Some(&mut(ref mut world,false)) = self.game_state.data.worlds.get_mut(player.world as us...
{ //Controllers if !self.paused{ for mut controller in self.controllers.iter_mut(){ controller.update(args,&self.game_state.data); } } //Key repeat for (key,time_left) in self.key_down.iter_mut(){ while{ *time_left-= args.dt; *time_left <= 0.0 }{ *time_left = if let Some(mapping) ...
identifier_body
types.rs
use core::fmt; use core::ops::*; pub use kernel::mm::{PhysAddrConv, MappedAddrConv, VirtAddrConv}; #[derive(Eq, PartialEq, Ord, PartialOrd, Clone, Copy, Debug, Default)] pub struct PhysAddr(pub usize); #[derive(Eq, PartialEq, Ord, PartialOrd, Clone, Copy, Debug, Default)] pub struct MappedAddr(pub usize); #[derive(...
else { PhysAddr(self.0) } } } impl MappedAddrConv for MappedAddr { fn to_phys(&self) -> PhysAddr { if self >= &PHYSMAP { PhysAddr(self.0 - PHYSMAP.0) } else { PhysAddr(self.0) } } }
{ PhysAddr(self.0 - VIRT.0) }
conditional_block
types.rs
use core::fmt; use core::ops::*; pub use kernel::mm::{PhysAddrConv, MappedAddrConv, VirtAddrConv}; #[derive(Eq, PartialEq, Ord, PartialOrd, Clone, Copy, Debug, Default)] pub struct PhysAddr(pub usize); #[derive(Eq, PartialEq, Ord, PartialOrd, Clone, Copy, Debug, Default)] pub struct MappedAddr(pub usize); #[derive(...
(pub usize); enable_unsigned_ops!(PhysAddr); enable_unsigned_ops!(MappedAddr); enable_unsigned_ops!(VirtAddr); const VIRT : VirtAddr = VirtAddr(0xFFFFFF0000000000); const PHYSMAP : MappedAddr = MappedAddr(0xFFFF800000000000); impl PhysAddrConv for PhysAddr { fn to_mapped(&self) -> MappedAddr { if self.0 ...
VirtAddr
identifier_name
types.rs
use core::fmt; use core::ops::*; pub use kernel::mm::{PhysAddrConv, MappedAddrConv, VirtAddrConv}; #[derive(Eq, PartialEq, Ord, PartialOrd, Clone, Copy, Debug, Default)] pub struct PhysAddr(pub usize); #[derive(Eq, PartialEq, Ord, PartialOrd, Clone, Copy, Debug, Default)] pub struct MappedAddr(pub usize); #[derive(...
impl MappedAddrConv for MappedAddr { fn to_phys(&self) -> PhysAddr { if self >= &PHYSMAP { PhysAddr(self.0 - PHYSMAP.0) } else { PhysAddr(self.0) } } }
} }
random_line_split
catalog.rs
// Copyright 2017 Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable...
path, err); Vec::new() } } }) .collect::<Vec<_>>(); PluginCatalog::new(&plugins) } pub fn new(plugins: &[PluginDescription]) -> Self { let mut items = HashMap::with_capacity(plu...
Ok(plugins) => plugins, Err(err) => { eprintln!("error loading plugins from {:?}, error:\n{:?}",
random_line_split
catalog.rs
// Copyright 2017 Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable...
(&'a self) -> Box<Iterator<Item=&'a PluginDescription> + 'a> { Box::new(self.items.values()) } /// Returns an iterator over all plugin names in the catalog, /// in arbitrary order. pub fn iter_names(&'a self) -> Box<Iterator<Item=&'a PluginName> + 'a> { Box::new(self.items.keys()) } ...
iter
identifier_name
catalog.rs
// Copyright 2017 Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable...
pub fn new(plugins: &[PluginDescription]) -> Self { let mut items = HashMap::with_capacity(plugins.len()); for plugin in plugins { if items.contains_key(&plugin.name) { eprintln!("Duplicate plugin name.\n 1: {:?}\n 2: {:?}", plugin, items.get(...
{ let plugins = paths.iter() .flat_map(|path| { match load_plugins(path) { Ok(plugins) => plugins, Err(err) => { eprintln!("error loading plugins from {:?}, error:\n{:?}", path, err); ...
identifier_body
catalog.rs
// Copyright 2017 Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable...
items.insert(plugin.name.to_owned(), plugin.to_owned()); } PluginCatalog { items } } /// Returns an iterator over all plugins in the catalog, in arbitrary order. pub fn iter(&'a self) -> Box<Iterator<Item=&'a PluginDescription> + 'a> { Box::new(self.items.values()) }...
{ eprintln!("Duplicate plugin name.\n 1: {:?}\n 2: {:?}", plugin, items.get(&plugin.name)); continue }
conditional_block
lib.rs
//! The command-line tool works in the following order:
//! //! 1. [`RemoteMounts::load`](struct.RemoteMounts.html#method.load) is called to load the contents //! of `/etc/mtab` into an internal struct. //! 2. [`RemoteMounts::into_current_dir`](struct.RemoteMounts.html#method.into_current_dir) is //! called to convert the above into a [`Location`](enum.Location.html)....
random_line_split
mod.rs
/** * Flow - Realtime log analyzer * Copyright (C) 2016 Daniel Mircea * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later ve...
pub mod frame; pub mod content; pub mod navigation; pub mod menu; pub mod search; pub mod input; pub mod event; pub mod readline; pub mod color; pub mod printer; pub mod highlighter; pub mod rendered_line;
* along with this program. If not, see <http://www.gnu.org/licenses/>. */
random_line_split
associated-const-ambiguity-report.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 ...
{ assert_eq!(1, X); }
identifier_body
associated-const-ambiguity-report.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 ...
() { assert_eq!(1, X); }
main
identifier_name
fun.rs
use allegro5::*; //~ use std::cmp::{max, min}; use std::num::abs; use world::{World, TILE_SIZE}; use camera::Camera; use util::intersect_rect; use gfx::Gfx; pub struct Demon { pub x: i32, pub y: i32, pub vx: i32, pub vy: i32, pub dead: bool, pub moving_to_center: bool, pub active: bool, pub w: i32, pub h:...
pub fn new(x: i32, y: i32) -> Demon { Demon { x: x - 12, y: y - 12, vx: 0, vy: 0, moving_to_center: false, w: 24, h: 24, dead: false, active: false, } } pub fn update(&mut self, world: &World, player_x: i32, player_y: i32, player_w: i32, player_h: i32) -> bool { if self.dead ...
impl Demon {
random_line_split
fun.rs
use allegro5::*; //~ use std::cmp::{max, min}; use std::num::abs; use world::{World, TILE_SIZE}; use camera::Camera; use util::intersect_rect; use gfx::Gfx; pub struct
{ pub x: i32, pub y: i32, pub vx: i32, pub vy: i32, pub dead: bool, pub moving_to_center: bool, pub active: bool, pub w: i32, pub h: i32, } impl Demon { pub fn new(x: i32, y: i32) -> Demon { Demon { x: x - 12, y: y - 12, vx: 0, vy: 0, moving_to_center: false, w: 24, h: 24, dea...
Demon
identifier_name
fun.rs
use allegro5::*; //~ use std::cmp::{max, min}; use std::num::abs; use world::{World, TILE_SIZE}; use camera::Camera; use util::intersect_rect; use gfx::Gfx; pub struct Demon { pub x: i32, pub y: i32, pub vx: i32, pub vy: i32, pub dead: bool, pub moving_to_center: bool, pub active: bool, pub w: i32, pub h:...
, None => { self.vx = 0; self.vy = 0; } } } } let (nx, ny) = world.checked_move(self.x, self.y, self.w, self.h, self.vx, self.vy, true); if nx == self.x && ny == self.y && (self.vx!= 0 || self.vy!= 0) { // Stuck, move to tile center and try again self.moving_to_center...
{ let (sx, sy) = a.get_shift(); self.vx = sx; self.vy = sy; self.active = true; }
conditional_block
variance-cell-is-invariant.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 ...
use std::cell::Cell; struct Foo<'a> { x: Cell<Option<&'a int>>, } fn use_<'short,'long>(c: Foo<'short>, s: &'short int, l: &'long int, _where:Option<&'short &'long ()>) { let _: Foo<'long> = c; //~ ERROR mismatched types } fn main() { }
random_line_split
variance-cell-is-invariant.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
routing_client.rs
// Copyright 2015 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"). // // ...
(&self, location: Authority, data: Data) { let _ = self.action_sender.send(Action::ClientSendContent( location, Content::ExternalRequest(ExternalRequest::Delete(data)))); } /// Signal to RoutingNode that it needs to refuse new messages and handle all outstanding /// ...
delete_request
identifier_name
routing_client.rs
// Copyright 2015 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"). // // ...
let _ = self.action_sender.send(Action::ClientSendContent( location, Content::ExternalRequest(ExternalRequest::Post(data)))); } /// Remove something from the network pub fn delete_request(&self, location: Authority, data: Data) { let _ = self.action_sender.se...
Content::ExternalRequest(ExternalRequest::Put(data)))); } /// Change something already on the network pub fn post_request(&self, location: Authority, data: Data) {
random_line_split
cpu.rs
use anyhow::{anyhow, Result}; use cnx::text::{Attributes, Text}; use cnx::widgets::{Widget, WidgetStream}; use std::fs::File; use std::io::BufRead; use std::io::BufReader; use std::time::Duration; use tokio::time; use tokio_stream::wrappers::IntervalStream; use tokio_stream::StreamExt; /// Represents CPU widget used t...
_ => return Err(anyhow!("Missing data in /proc/stat")), } Ok(cpu_data) } } impl Widget for Cpu { fn into_stream(mut self: Box<Self>) -> Result<WidgetStream> { let ten_seconds = Duration::from_secs(10); let interval = time::interval(ten_seconds); let stream =...
{ let user_time = user.parse()?; let nice_time = nice.parse()?; let system_time = system.parse()?; let idle_time = idle.parse()?; let iowait_time = iowait.parse()?; cpu_data.user_time = user_time; cpu_data.ni...
conditional_block
cpu.rs
use anyhow::{anyhow, Result}; use cnx::text::{Attributes, Text}; use cnx::widgets::{Widget, WidgetStream}; use std::fs::File; use std::io::BufRead; use std::io::BufReader; use std::time::Duration; use tokio::time; use tokio_stream::wrappers::IntervalStream; use tokio_stream::StreamExt; /// Represents CPU widget used t...
(mut self: Box<Self>) -> Result<WidgetStream> { let ten_seconds = Duration::from_secs(10); let interval = time::interval(ten_seconds); let stream = IntervalStream::new(interval).map(move |_| self.tick()); Ok(Box::pin(stream)) } }
into_stream
identifier_name
cpu.rs
use anyhow::{anyhow, Result}; use cnx::text::{Attributes, Text}; use cnx::widgets::{Widget, WidgetStream}; use std::fs::File; use std::io::BufRead; use std::io::BufReader; use std::time::Duration; use tokio::time; use tokio_stream::wrappers::IntervalStream; use tokio_stream::StreamExt; /// Represents CPU widget used t...
cpu_data.user_time = user_time; cpu_data.nice_time = nice_time; cpu_data.system_time = system_time; cpu_data.idle_time = idle_time; cpu_data.iowait_time = iowait_time; cpu_data.total_time = user_time + nice_time + system_tim...
let idle_time = idle.parse()?; let iowait_time = iowait.parse()?;
random_line_split
geometry.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use cssparser::ToCss; use euclid::length::Length; use euclid::num::Zero; use euclid::point::Point2D; use euclid::...
{} /// One CSS "px" in the coordinate system of the "initial viewport": /// http://www.w3.org/TR/css-device-adapt/#initial-viewport /// /// ViewportPx is equal to ScreenPx times a "page zoom" factor controlled by the user. This is /// the desktop-style "full page" zoom that enlarges content but then reflows the layo...
ScreenPx
identifier_name
geometry.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use cssparser::ToCss; use euclid::length::Length; use euclid::num::Zero; use euclid::point::Point2D; use euclid::...
#[inline] pub fn from_px(px: i32) -> Au { Au((px * 60) as i32) } #[inline] pub fn from_page_px(px: Length<PagePx, f32>) -> Au { Au((px.get() * 60f32) as i32) } /// Rounds this app unit down to the pixel towards zero and returns it. #[inline] pub fn to_px(self) -> i3...
pub fn scale_by(self, factor: f32) -> Au { Au(((self.0 as f32) * factor) as i32) }
random_line_split
geometry.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use cssparser::ToCss; use euclid::length::Length; use euclid::num::Zero; use euclid::point::Point2D; use euclid::...
} impl ToCss for Au { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { write!(dest, "{}px", self.to_f64_px()) } } impl Add for Au { type Output = Au; #[inline] fn add(self, other: Au) -> Au { Au(self.0.wrapping_add(other.0)) } } impl Sub for Au { ty...
{ write!(f, "{}px", self.to_f64_px()) }
identifier_body
geometry.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use cssparser::ToCss; use euclid::length::Length; use euclid::num::Zero; use euclid::point::Point2D; use euclid::...
; } #[inline] pub fn from_f32_px(px: f32) -> Au { Au((px * 60f32) as i32) } #[inline] pub fn from_pt(pt: f64) -> Au { Au::from_f64_px(pt_to_px(pt)) } #[inline] pub fn from_f64_px(px: f64) -> Au { Au((px * 60.) as i32) } } // assumes 72 points per inch,...
{ return Au(self.0 - res) }
conditional_block
comparator.rs
// rust way of ord use std::cmp::Ordering; pub trait Comparator<T> { fn compare(&self, v: &T, w: &T) -> Ordering; fn less(&self, v: &T, w: &T) -> bool { self.compare(v, w) == Ordering::Less } } impl<T, F> Comparator<T> for F where F: Send + Sync + Fn(&T, &T) -> Ordering { fn compare(&self, v...
{ use rand::{thread_rng, Rng}; fn is_reverse_sorted<T: PartialOrd>(a: &[T]) -> bool { for i in 1 .. a.len() { if a[i] > a[i-1] { return false; } } true } let mut array = thread_rng().gen_iter().take(10).collect::<Vec<u32>>(); // FIXME...
identifier_body
comparator.rs
// rust way of ord use std::cmp::Ordering; pub trait Comparator<T> { fn compare(&self, v: &T, w: &T) -> Ordering; fn less(&self, v: &T, w: &T) -> bool { self.compare(v, w) == Ordering::Less } } impl<T, F> Comparator<T> for F where F: Send + Sync + Fn(&T, &T) -> Ordering { fn compare(&self, v...
use rand::{thread_rng, Rng}; fn is_reverse_sorted<T: PartialOrd>(a: &[T]) -> bool { for i in 1.. a.len() { if a[i] > a[i-1] { return false; } } true } let mut array = thread_rng().gen_iter().take(10).collect::<Vec<u32>>(); // FIXME: d...
#[test] fn test_insertion_sort_using_a_comparator() {
random_line_split
comparator.rs
// rust way of ord use std::cmp::Ordering; pub trait Comparator<T> { fn compare(&self, v: &T, w: &T) -> Ordering; fn less(&self, v: &T, w: &T) -> bool { self.compare(v, w) == Ordering::Less } } impl<T, F> Comparator<T> for F where F: Send + Sync + Fn(&T, &T) -> Ordering { fn compare(&self, v...
} true } let mut array = thread_rng().gen_iter().take(10).collect::<Vec<u32>>(); // FIXME: due to https://github.com/rust-lang/rust/issues/24680 // the Comparator closure's type can't be inferred! insertion_sort(&mut array, |v: &u32, w: &u32| w.cmp(v) ); assert!(is_reverse_sort...
{ return false; }
conditional_block
comparator.rs
// rust way of ord use std::cmp::Ordering; pub trait Comparator<T> { fn compare(&self, v: &T, w: &T) -> Ordering; fn less(&self, v: &T, w: &T) -> bool { self.compare(v, w) == Ordering::Less } } impl<T, F> Comparator<T> for F where F: Send + Sync + Fn(&T, &T) -> Ordering { fn compare(&self, v...
<T: PartialOrd, C: Comparator<T>>(a: &mut [T], comparator: C) { let n = a.len(); for i in 0.. n { for j in (1.. i + 1).rev() { if comparator.less(&a[j], &a[j-1]) { a.swap(j, j-1); } } } } #[test] fn test_insertion_sort_using_a_comparator() { use ...
insertion_sort
identifier_name
flags.rs
mat!(match_flag_case, "(?i)abc", "ABC", Some((0, 3))); mat!(match_flag_weird_case, "(?i)a(?-i)bc", "Abc", Some((0, 3))); mat!(match_flag_weird_case_not, "(?i)a(?-i)bc", "ABC", None); mat!(match_flag_case_dotnl, "(?is)a.", "A\n", Some((0, 2))); mat!(match_flag_case_dotnl_toggle, "(?is)a.(?-is)a.", "A\nab", Some((0, 4)))...
mat!(match_flag_ungreedy, "(?U)a+", "aa", Some((0, 1))); mat!(match_flag_ungreedy_greedy, "(?U)a+?", "aa", Some((0, 2))); mat!(match_flag_ungreedy_noop, "(?U)(?-U)a+", "aa", Some((0, 2)));
mat!(match_flag_multi, "(?m)(?:^\\d+$\n?)+", "123\n456\n789", Some((0, 11)));
random_line_split
mod.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use common::SourceLocationKey; use fixture_tests::Fixture; use graphql_ir::{build, ExecutableDefinition, Program}; use graphql_sy...
.map_err(|errors| { errors .into_iter() .map(|error| format!("{:?}", error)) .collect::<Vec<_>>() .join("\n\n") }) }
{ let source_location = SourceLocationKey::standalone(fixture.file_name); let ast = parse_executable(fixture.content, source_location).unwrap(); let ir = build(&TEST_SCHEMA, &ast.definitions).unwrap(); let program = Program::from_definitions(Arc::clone(&TEST_SCHEMA), ir); build(&TEST_SCHEMA, &ast.d...
identifier_body
mod.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use common::SourceLocationKey; use fixture_tests::Fixture; use graphql_ir::{build, ExecutableDefinition, Program}; use graphql_sy...
(fixture: &Fixture<'_>) -> Result<String, String> { let source_location = SourceLocationKey::standalone(fixture.file_name); let ast = parse_executable(fixture.content, source_location).unwrap(); let ir = build(&TEST_SCHEMA, &ast.definitions).unwrap(); let program = Program::from_definitions(Arc::clone(&...
transform_fixture
identifier_name
mod.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use common::SourceLocationKey; use fixture_tests::Fixture; use graphql_ir::{build, ExecutableDefinition, Program}; use graphql_sy...
.join("\n\n\n\n") }) .map_err(|errors| { errors .into_iter() .map(|error| format!("{:?}", error)) .collect::<Vec<_>>() .join("\n\n") }) }
} }) .collect::<Vec<String>>()
random_line_split
mod.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use common::SourceLocationKey; use fixture_tests::Fixture; use graphql_ir::{build, ExecutableDefinition, Program}; use graphql_sy...
}) .collect::<Vec<String>>() .join("\n\n\n\n") }) .map_err(|errors| { errors .into_iter() .map(|error| format!("{:?}", error)) .collect::<Vec<_>>() .join("\n\n") }) }
{ None }
conditional_block
lib.rs
// Copyright 2015 juggle-tux // This file is part of srttool. // // srttool is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // sr...
; let mut content = String::with_capacity(128); while let Some(text) = self.buf.next() { self.line += 1; match text { Ok(text) => { if text == "" { break; } content = content + &t...
{ return Some(Err(ParseError::InvalidTimeString)); }
conditional_block
lib.rs
// Copyright 2015 juggle-tux // This file is part of srttool. // // srttool is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // sr...
} }
random_line_split
lib.rs
// Copyright 2015 juggle-tux // This file is part of srttool. // // srttool is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // sr...
(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { write!(f, "{}\n{}\n", self.start_end, self.content) } } /// a BlockReader pub struct BlockReader<B> { buf: Lines<B>, /// last line read line: u64, } impl<B> BlockReader<B> { /// returns the line number of the last line readed ...
fmt
identifier_name
lib.rs
// Copyright 2015 juggle-tux // This file is part of srttool. // // srttool is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // sr...
return Some(Err(ParseError::InvalidTimeString)); }; let mut content = String::with_capacity(128); while let Some(text) = self.buf.next() { self.line += 1; match text { Ok(text) => { if text == "" { b...
{ // idx if let Some(Ok(idx)) = self.buf.next() { self.line += 1; if idx == "" { return None; //File ends with final new line } else if !is_idx(&idx) { return Some(Err(ParseError::InvalidIndex)); } } else { ...
identifier_body
mapper.rs
use super::table::{self, Table, Level4}; use super::{VirtualAddress, PhysicalAddress, PAGE_SIZE, Page}; use super::entry::{EntryFlags}; use memory::{Frame, FrameAllocator}; use core::ptr::Unique; pub struct Mapper { p4: Unique<Table<Level4>>, } impl Mapper { pub unsafe fn new() -> Mapper { Mapper { ...
.and_then(|p1| p1[page.p1_index()].pointed_frame()) } }
pub fn translate_page(&self, page: Page) -> Option<Frame> { self.p4().next_table(page.p4_index()) .and_then(|p3| p3.next_table(page.p3_index())) .and_then(|p2| p2.next_table(page.p2_index()))
random_line_split
mapper.rs
use super::table::{self, Table, Level4}; use super::{VirtualAddress, PhysicalAddress, PAGE_SIZE, Page}; use super::entry::{EntryFlags}; use memory::{Frame, FrameAllocator}; use core::ptr::Unique; pub struct Mapper { p4: Unique<Table<Level4>>, } impl Mapper { pub unsafe fn new() -> Mapper { Mapper { ...
pub fn translate(&self, virtual_address: VirtualAddress) -> Option<PhysicalAddress> { let offset = virtual_address.get() % PAGE_SIZE; self.translate_page(Page::containing_address(virtual_address)) .map(|frame| PhysicalAddress::new(frame.start_address().get() + offset)) } pub fn...
{ unsafe { self.p4.as_mut() } }
identifier_body
mapper.rs
use super::table::{self, Table, Level4}; use super::{VirtualAddress, PhysicalAddress, PAGE_SIZE, Page}; use super::entry::{EntryFlags}; use memory::{Frame, FrameAllocator}; use core::ptr::Unique; pub struct Mapper { p4: Unique<Table<Level4>>, } impl Mapper { pub unsafe fn new() -> Mapper { Mapper { ...
<A>(&mut self, frame: Frame, flags: EntryFlags, allocator: &mut A) where A: FrameAllocator { let page = Page::containing_address(VirtualAddress::new(frame.start_address().get())); self.map_to(page, frame, flags, allocator) } pub fn unmap<A>(&mut self, page: Page, allocator: &mut A) where A: Fra...
identity_map
identifier_name
fs.rs
// This file is part of the uutils coreutils package. // // (c) Joseph Crail <jbcrail@gmail.com> // (c) Jian Zeng <anonymousknight96 AT gmail.com> // // For the full copyright and license information, please view the LICENSE // file that was distributed with this source code. #[cfg(target_os = "redox")] extern crate t...
result.push(parts.last().unwrap()); match resolve(&result) { Err(e) => { if can_mode == CanonicalizeMode::Existing { return Err(e); } } Ok(path) => { result.pop(); result.push(path); ...
{ for part in parts[..parts.len() - 1].iter() { result.push(part); if can_mode == CanonicalizeMode::None { continue; } match resolve(&result) { Err(e) => match can_mode { CanonicalizeMode::Missing => continue, ...
conditional_block
fs.rs
// This file is part of the uutils coreutils package. // // (c) Joseph Crail <jbcrail@gmail.com> // (c) Jian Zeng <anonymousknight96 AT gmail.com> // // For the full copyright and license information, please view the LICENSE // file that was distributed with this source code. #[cfg(target_os = "redox")] extern crate t...
result = p; } result.pop(); } Component::CurDir => (), Component::RootDir | Component::Normal(_) | Component::Prefix(_) => { result.push(comp.as_os_str()) } } } result.into() } #[derive(C...
random_line_split
fs.rs
// This file is part of the uutils coreutils package. // // (c) Joseph Crail <jbcrail@gmail.com> // (c) Jian Zeng <anonymousknight96 AT gmail.com> // // For the full copyright and license information, please view the LICENSE // file that was distributed with this source code. #[cfg(target_os = "redox")] extern crate t...
() -> bool { termion::is_tty(&io::stderr()) }
is_stderr_interactive
identifier_name
fs.rs
// This file is part of the uutils coreutils package. // // (c) Joseph Crail <jbcrail@gmail.com> // (c) Jian Zeng <anonymousknight96 AT gmail.com> // // For the full copyright and license information, please view the LICENSE // file that was distributed with this source code. #[cfg(target_os = "redox")] extern crate t...
result.into() } #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum CanonicalizeMode { None, Normal, Existing, Missing, } fn resolve<P: AsRef<Path>>(original: P) -> IOResult<PathBuf> { const MAX_LINKS_FOLLOWED: u32 = 255; let mut followed = 0; let mut result = original.as_ref().to_p...
{ if path.components().all(|e| e != Component::ParentDir) { return path.into(); } let root = Component::RootDir.as_os_str(); let mut result = env::current_dir().unwrap_or(PathBuf::from(root)); for comp in path.components() { match comp { Component::ParentDir => { ...
identifier_body
point3d.rs
use serde::de::{self, Deserialize, Deserializer, SeqAccess, Visitor}; use serde::ser::{Serialize, SerializeTupleStruct, Serializer}; use std::borrow::Borrow; use std::{fmt, ops}; use crate::vector3d::Vector3D; #[derive(Clone, Debug, Default)] pub struct Point3D { pub x: i32, pub y: i32, pub z: i32, } imp...
Ok(Self { x: parts[0] .parse() .map_err(|err| format!("Could not parse x coordinate: {:?}", err))?, y: parts[1] .parse() .map_err(|err| format!("Could not parse y coordinate: {:?}", err))?, z: parts[2] ...
{ return Err("Invalid point -- must contain 3 comma-separated coordinates".to_owned()); }
conditional_block
point3d.rs
use serde::de::{self, Deserialize, Deserializer, SeqAccess, Visitor}; use serde::ser::{Serialize, SerializeTupleStruct, Serializer}; use std::borrow::Borrow; use std::{fmt, ops}; use crate::vector3d::Vector3D; #[derive(Clone, Debug, Default)] pub struct Point3D { pub x: i32, pub y: i32, pub z: i32, } imp...
(&self) -> bool { self.x == 0 && self.y == 0 && self.z == 0 } pub fn to_vec(&self) -> Vector3D { Vector3D::new(self.x, self.y, self.z) } } impl<T> ops::Sub<T> for Point3D where T: Borrow<Self>, { type Output = Vector3D; fn sub(self, rhs: T) -> Self::Output { Vector3D::...
is_default
identifier_name
point3d.rs
use serde::de::{self, Deserialize, Deserializer, SeqAccess, Visitor}; use serde::ser::{Serialize, SerializeTupleStruct, Serializer}; use std::borrow::Borrow; use std::{fmt, ops}; use crate::vector3d::Vector3D; #[derive(Clone, Debug, Default)] pub struct Point3D { pub x: i32, pub y: i32, pub z: i32, } imp...
pub fn to_vec(&self) -> Vector3D { Vector3D::new(self.x, self.y, self.z) } } impl<T> ops::Sub<T> for Point3D where T: Borrow<Self>, { type Output = Vector3D; fn sub(self, rhs: T) -> Self::Output { Vector3D::new( self.x - rhs.borrow().x, self.y - rhs.borrow...
{ self.x == 0 && self.y == 0 && self.z == 0 }
identifier_body
point3d.rs
use serde::de::{self, Deserialize, Deserializer, SeqAccess, Visitor}; use serde::ser::{Serialize, SerializeTupleStruct, Serializer}; use std::borrow::Borrow; use std::{fmt, ops}; use crate::vector3d::Vector3D; #[derive(Clone, Debug, Default)] pub struct Point3D { pub x: i32, pub y: i32, pub z: i32, } imp...
impl<T> ops::Sub<T> for &Point3D where T: Borrow<Self>, { type Output = Vector3D; fn sub(self, rhs: T) -> Self::Output { Vector3D::new( self.x - rhs.borrow().x, self.y - rhs.borrow().y, self.z - rhs.borrow().z, ) } } impl<'de> Deserialize<'de> for P...
random_line_split
handles.rs
//! Handles to an operator's input and output streams. use std::rc::Rc; use std::cell::RefCell; use progress::Timestamp; use progress::count_map::CountMap; use dataflow::channels::pullers::Counter as PullCounter; use dataflow::channels::pushers::Counter as PushCounter; use dataflow::channels::pushers::buffer::{Buffer,...
pub fn new_output_handle<'a, T: Timestamp, D, P: Push<(T, Content<D>)>>(push_buffer: &'a mut Buffer<T, D, PushCounter<T, D, P>>) -> OutputHandle<'a, T, D, P> { OutputHandle { push_buffer: push_buffer, } }
} /// Constructs an output handle. /// Declared separately so that it can be kept private when `OutputHandle` is re-exported.
random_line_split
handles.rs
//! Handles to an operator's input and output streams. use std::rc::Rc; use std::cell::RefCell; use progress::Timestamp; use progress::count_map::CountMap; use dataflow::channels::pullers::Counter as PullCounter; use dataflow::channels::pushers::Counter as PushCounter; use dataflow::channels::pushers::buffer::{Buffer,...
} /// Constructs an output handle. /// Declared separately so that it can be kept private when `OutputHandle` is re-exported. pub fn new_output_handle<'a, T: Timestamp, D, P: Push<(T, Content<D>)>>(push_buffer: &'a mut Buffer<T, D, PushCounter<T, D, P>>) -> OutputHandle<'a, T, D, P> { OutputHandle { push_...
{ self.push_buffer.session(cap) }
identifier_body
handles.rs
//! Handles to an operator's input and output streams. use std::rc::Rc; use std::cell::RefCell; use progress::Timestamp; use progress::count_map::CountMap; use dataflow::channels::pullers::Counter as PullCounter; use dataflow::channels::pushers::Counter as PushCounter; use dataflow::channels::pushers::buffer::{Buffer,...
<'a, T: Timestamp, D: 'a> { pull_counter: &'a mut PullCounter<T, D>, internal: Rc<RefCell<CountMap<T>>>, } impl<'a, T: Timestamp, D> InputHandle<'a, T, D> { /// Reads the next input buffer (at some timestamp `t`) and a corresponding capability for `t`. /// The timestamp `t` of the input buffer can be r...
InputHandle
identifier_name
timer.rs
//! APU timer implementation. #[derive(Copy, Clone, Debug)] pub struct Timer { /// Divider of this timer pub div: u8, /// Current value of the counter. Limited to 4 bits (the upper 4 bits are always 0) pub val: u8, enabled: bool, /// Counted up at the same speed as the APU runs. When it reaches...
pub fn set_enable(&mut self, enable: bool) { if!self.enabled && enable { self.stage2 = 0; self.val = 0; } self.enabled = enable; } pub fn enabled(&mut self) -> bool { self.enabled } }
random_line_split
timer.rs
//! APU timer implementation. #[derive(Copy, Clone, Debug)] pub struct Timer { /// Divider of this timer pub div: u8, /// Current value of the counter. Limited to 4 bits (the upper 4 bits are always 0) pub val: u8, enabled: bool, /// Counted up at the same speed as the APU runs. When it reaches...
() -> Timer { Timer::default() } /// Update the timer, applying a base-divisor (128 for Timer 0/1, 16 for Timer 2) pub fn update(&mut self, base_div: u8, cy: u8) { self.stage1 += cy; if self.enabled { self.stage2 += self.stage1 as u16 / base_div as u16; } self.stage1 %= base_div; ...
new
identifier_name
timer.rs
//! APU timer implementation. #[derive(Copy, Clone, Debug)] pub struct Timer { /// Divider of this timer pub div: u8, /// Current value of the counter. Limited to 4 bits (the upper 4 bits are always 0) pub val: u8, enabled: bool, /// Counted up at the same speed as the APU runs. When it reaches...
} pub fn set_enable(&mut self, enable: bool) { if!self.enabled && enable { self.stage2 = 0; self.val = 0; } self.enabled = enable; } pub fn enabled(&mut self) -> bool { self.enabled } }
{ let real_div: u16 = if self.div == 0 { 256 } else { self.div as u16 }; self.val += (self.stage2 / real_div) as u8; self.stage2 %= real_div; self.val &= 0x0f; // It's a 4-bit counter }
conditional_block
timer.rs
//! APU timer implementation. #[derive(Copy, Clone, Debug)] pub struct Timer { /// Divider of this timer pub div: u8, /// Current value of the counter. Limited to 4 bits (the upper 4 bits are always 0) pub val: u8, enabled: bool, /// Counted up at the same speed as the APU runs. When it reaches...
/// Update the timer, applying a base-divisor (128 for Timer 0/1, 16 for Timer 2) pub fn update(&mut self, base_div: u8, cy: u8) { self.stage1 += cy; if self.enabled { self.stage2 += self.stage1 as u16 / base_div as u16; } self.stage1 %= base_div; if self.enabled { ...
{ Timer::default() }
identifier_body
joint.rs
#![allow(missing_docs)] // For downcast. use downcast_rs::Downcast; use na::{DVectorSliceMut, RealField}; use crate::math::{Isometry, JacobianSliceMut, Vector, Velocity}; use crate::object::{BodyPartHandle, Multibody, MultibodyLink}; use crate::solver::{ConstraintSet, GenericNonlinearConstraint, IntegrationParameters...
/// Initialize and generate the i-th position constraints to enforce, e.g., joint limits. fn position_constraint( &self, _i: usize, _multibody: &Multibody<N>, _link: &MultibodyLink<N>, _handle: BodyPartHandle<()>, _dof_id: usize, _jacobians: &mut [N], ...
{ 0 }
identifier_body
joint.rs
#![allow(missing_docs)] // For downcast. use downcast_rs::Downcast; use na::{DVectorSliceMut, RealField}; use crate::math::{Isometry, JacobianSliceMut, Vector, Velocity}; use crate::object::{BodyPartHandle, Multibody, MultibodyLink}; use crate::solver::{ConstraintSet, GenericNonlinearConstraint, IntegrationParameters...
/// The maximum number of impulses needed by this joints for /// its constraints. fn nimpulses(&self) -> usize { // FIXME: keep this? self.ndofs() * 3 } /// Maximum number of velocity constrains that can be generated by this joint. fn num_velocity_constraints(&self) -> usize { ...
random_line_split
joint.rs
#![allow(missing_docs)] // For downcast. use downcast_rs::Downcast; use na::{DVectorSliceMut, RealField}; use crate::math::{Isometry, JacobianSliceMut, Vector, Velocity}; use crate::object::{BodyPartHandle, Multibody, MultibodyLink}; use crate::solver::{ConstraintSet, GenericNonlinearConstraint, IntegrationParameters...
(&self) -> usize { 0 } /// Initialize and generate velocity constraints to enforce, e.g., joint limits and motors. fn velocity_constraints( &self, _params: &IntegrationParameters<N>, _multibody: &Multibody<N>, _link: &MultibodyLink<N>, _assembly_id: usize, ...
num_velocity_constraints
identifier_name
type-param-constraints.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 main() { p_foo(r(10)); p_foo::<Box<_>>(box r(10)); p_foo::<Box<_>>(box 10); p_foo(10); s_foo::<Box<_>>(box 10); s_foo(10); u_foo::<Box<_>>(box 10); u_foo(10); }
{ r { i: i } }
identifier_body
type-param-constraints.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...
<T:Send>(_unique: T) { } struct r { i: isize, } impl Drop for r { fn drop(&mut self) {} } fn r(i:isize) -> r { r { i: i } } pub fn main() { p_foo(r(10)); p_foo::<Box<_>>(box r(10)); p_foo::<Box<_>>(box 10); p_foo(10); s_foo::<Box<_>>(box 10); s_foo(10); u_foo::<B...
u_foo
identifier_name
type-param-constraints.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...
i: isize, } impl Drop for r { fn drop(&mut self) {} } fn r(i:isize) -> r { r { i: i } } pub fn main() { p_foo(r(10)); p_foo::<Box<_>>(box r(10)); p_foo::<Box<_>>(box 10); p_foo(10); s_foo::<Box<_>>(box 10); s_foo(10); u_foo::<Box<_>>(box 10); u_foo(10); }
struct r {
random_line_split
generate_lockfile.rs
use std::env; use cargo::ops; use cargo::util::{CliResult, CliError, Config}; use cargo::util::important_paths::find_root_manifest_for_cwd; #[derive(RustcDecodable)] struct Options { flag_manifest_path: Option<String>, flag_verbose: bool, } pub const USAGE: &'static str = " Generate the lockfile for a projec...
{ debug!("executing; cmd=cargo-generate-lockfile; args={:?}", env::args().collect::<Vec<_>>()); config.shell().set_verbose(options.flag_verbose); let root = try!(find_root_manifest_for_cwd(options.flag_manifest_path)); ops::generate_lockfile(&root, config) .map(|_| None).map_err(|err| CliError:...
identifier_body
generate_lockfile.rs
use std::env; use cargo::ops; use cargo::util::{CliResult, CliError, Config}; use cargo::util::important_paths::find_root_manifest_for_cwd; #[derive(RustcDecodable)] struct Options { flag_manifest_path: Option<String>, flag_verbose: bool, }
pub const USAGE: &'static str = " Generate the lockfile for a project Usage: cargo generate-lockfile [options] Options: -h, --help Print this message --manifest-path PATH Path to the manifest to generate a lockfile for -v, --verbose Use verbose output "; pub fn execute(optio...
random_line_split
generate_lockfile.rs
use std::env; use cargo::ops; use cargo::util::{CliResult, CliError, Config}; use cargo::util::important_paths::find_root_manifest_for_cwd; #[derive(RustcDecodable)] struct
{ flag_manifest_path: Option<String>, flag_verbose: bool, } pub const USAGE: &'static str = " Generate the lockfile for a project Usage: cargo generate-lockfile [options] Options: -h, --help Print this message --manifest-path PATH Path to the manifest to generate a lockfile for ...
Options
identifier_name
structure.rs
KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //! Generic algebraic structures use num_traits::{cast, Float}; use std::cmp; use std::iter; use std::ops::*; use approx; use angle::Rad; use num::{BaseFloat, BaseNum}; pub use...
/// Invert this matrix, returning a new matrix. `m.mul_m(m.invert())` is /// the identity matrix. Returns `None` if this matrix is not invertible /// (has a determinant of zero). fn invert(&self) -> Option<Self>; /// Test if this matrix is invertible. #[inline] fn is_invertible(&self) -> bo...
self.diagonal().sum() }
identifier_body
structure.rs
, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //! Generic algebraic structures use num_traits::{cast, Float}; use std::cmp; use std::iter; use std::ops::*; use approx; use angle::Rad; use num::{BaseFloat, BaseNum}; pub use num_...
-> Self { Self::one() } /// Transpose this matrix in-place. fn transpose_self(&mut self); /// Take the determinant of this matrix. fn determinant(&self) -> Self::Scalar; /// Return a vector containing the diagonal of this matrix. fn diagonal(&self) -> Self::ColumnRow; /// Ret...
entity()
identifier_name
structure.rs
KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //! Generic algebraic structures use num_traits::{cast, Float}; use std::cmp; use std::iter; use std::ops::*; use approx; use angle::Rad; use num::{BaseFloat, BaseNum}; pub use...
} /// Return the angle rotated by half a turn. #[inline] fn opposite(self) -> Self { Self::normalize(self + Self::turn_div_2()) } /// Returns the interior bisector of the two angles. #[inline] fn bisect(self, other: Self) -> Self { let half = cast(0.5f64).unwrap(); ...
rem }
conditional_block
structure.rs
ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //! Generic algebraic structures use num_traits::{cast, Float}; use std::cmp; use std::iter; use std::ops::*; use approx; use angle::Rad; use num::{BaseFloat, BaseNum}; pub...
/// pub trait EuclideanSpace: Copy + Clone where // FIXME: Ugly type signatures - blocked by rust-lang/rust#24092 Self: Array<Element = <Self as EuclideanSpace>::Scalar>, Self: Add<<Self as EuclideanSpace>::Diff, Output = Self>, Self: Sub<<Self as EuclideanSpace>::Diff, Output = Self>, Self: Sub<Se...
/// - [What is the difference between a point and a vector](http://math.stackexchange.com/q/645827)
random_line_split
blob.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::BlobBinding; use dom::bindings::codegen::Bindings::BlobBinding::BlobMethods;...
(&self) -> &[u8] { &self.bytes[self.bytes_start..self.bytes_end] } /// Get length of sliced bytes pub fn size(&self) -> u64 { (self.bytes_end as u64) - (self.bytes_start as u64) } } // https://w3c.github.io/FileAPI/#blob #[dom_struct] pub struct Blob { reflector_: Reflector, #...
get_bytes
identifier_name
blob.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::BlobBinding; use dom::bindings::codegen::Bindings::BlobBinding::BlobMethods;...
let relativeStart: i64 = match start { None => 0, Some(start) => { if start < 0 { max(size + start, 0) } else { min(start, size) } } }; let relativeEnd: i64 = match end { ...
impl DataSlice { /// Construct DataSlice from reference counted bytes pub fn new(bytes: Arc<Vec<u8>>, start: Option<i64>, end: Option<i64>) -> DataSlice { let size = bytes.len() as i64;
random_line_split
blob.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::BlobBinding; use dom::bindings::codegen::Bindings::BlobBinding::BlobMethods;...
, } }).collect::<Vec<u8>>() } impl BlobMethods for Blob { // https://w3c.github.io/FileAPI/#dfn-size fn Size(&self) -> u64 { self.data.size() } // https://w3c.github.io/FileAPI/#dfn-type fn Type(&self) -> DOMString { DOMString::from(self.typeString.clone()) ...
{ b.get_data().get_bytes().to_vec() }
conditional_block
debug.rs
use core::slice; use drivers::io::{Io, Pio}; use system::error::Result; pub fn
(ptr: *const u8, len: usize) -> Result<usize> { let bytes = unsafe { slice::from_raw_parts(ptr, len) }; if unsafe { ::ENV_PTR.is_some() } { ::env().console.lock().write(bytes); } else { let serial_status = Pio::<u8>::new(0x3F8 + 5); let mut serial_data = Pio::<u8>::new(0x3F8); ...
do_sys_debug
identifier_name
debug.rs
use core::slice; use drivers::io::{Io, Pio}; use system::error::Result; pub fn do_sys_debug(ptr: *const u8, len: usize) -> Result<usize> { let bytes = unsafe { slice::from_raw_parts(ptr, len) }; if unsafe { ::ENV_PTR.is_some() } { ::env().console.lock().write(bytes); } else { let serial_...
Ok(len) }
} }
random_line_split
debug.rs
use core::slice; use drivers::io::{Io, Pio}; use system::error::Result; pub fn do_sys_debug(ptr: *const u8, len: usize) -> Result<usize> { let bytes = unsafe { slice::from_raw_parts(ptr, len) }; if unsafe { ::ENV_PTR.is_some() } { ::env().console.lock().write(bytes); } else { let serial_...
} } Ok(len) }
{ while !serial_status.readf(0x20) {} serial_data.write(0x20); while !serial_status.readf(0x20) {} serial_data.write(8); }
conditional_block
debug.rs
use core::slice; use drivers::io::{Io, Pio}; use system::error::Result; pub fn do_sys_debug(ptr: *const u8, len: usize) -> Result<usize>
} } Ok(len) }
{ let bytes = unsafe { slice::from_raw_parts(ptr, len) }; if unsafe { ::ENV_PTR.is_some() } { ::env().console.lock().write(bytes); } else { let serial_status = Pio::<u8>::new(0x3F8 + 5); let mut serial_data = Pio::<u8>::new(0x3F8); for byte in bytes.iter() { whi...
identifier_body
ascii.rs
// This is a part of rust-encoding. // Copyright (c) 2013-2015, Kang Seonghoon. // See README.md and LICENSE.txt for details. //! 7-bit ASCII encoding. use libtww::std::mem; use libtww::std::convert::Into; use types::*; /** * ASCII, also known as ISO/IEC 646:US. * * It is both a basis and a lowest common denomina...
pub struct ASCIIEncoding; impl Encoding for ASCIIEncoding { fn name(&self) -> &'static str { "ascii" } fn raw_encoder(&self) -> Box<RawEncoder> { ASCIIEncoder::new() } fn raw_decoder(&self) -> Box<RawDecoder> { ASCIIDecoder::new() } } /// An encoder for ASCII. #[derive(...
#[derive(Clone, Copy)]
random_line_split