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 |
|---|---|---|---|---|
socket.rs | // Copyright 2013-2015, The Gtk-rs Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
use glib::translate::*;
use ffi;
use glib::object::Downcast;
use Widget;
glib_wrapper! {
... | () -> Socket {
assert_initialized_main_thread!();
unsafe { Widget::from_glib_none(ffi::gtk_socket_new()).downcast_unchecked() }
}
/*pub fn add_id(&self, window: Window) {
unsafe { ffi::gtk_socket_add_id(self.to_glib_none().0, window) };
}
pub fn get_id(&self) -> Window {
... | new | identifier_name |
service.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any lat... | &client_path.to_str().expect("DB path could not be converted to string.")
).map_err(::client::Error::Database)?);
let pruning = config.pruning;
let client = Client::new(config, &spec, db.clone(), miner, io_service.channel())?;
let snapshot_params = SnapServiceParams {
engine: spec.engine.clone(),
ge... | {
let panic_handler = PanicHandler::new_in_arc();
let io_service = IoService::<ClientIoMessage>::start()?;
panic_handler.forward_from(&io_service);
info!("Configured for {} using {} engine", Colour::White.bold().paint(spec.name.clone()), Colour::Yellow.bold().paint(spec.engine.name()));
let mut db_config = ... | identifier_body |
service.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any lat... | (&self) -> Arc<Client> {
self.client.clone()
}
/// Get snapshot interface.
pub fn snapshot_service(&self) -> Arc<SnapshotService> {
self.snapshot.clone()
}
/// Get network service component
pub fn io(&self) -> Arc<IoService<ClientIoMessage>> {
self.io_service.clone()
}
/// Set the actor to be notified ... | client | identifier_name |
service.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any lat... |
ClientIoMessage::FeedStateChunk(ref hash, ref chunk) => self.snapshot.feed_state_chunk(*hash, chunk),
ClientIoMessage::FeedBlockChunk(ref hash, ref chunk) => self.snapshot.feed_block_chunk(*hash, chunk),
ClientIoMessage::TakeSnapshot(num) => {
let client = self.client.clone();
let snapshot = self.snap... | {
if let Err(e) = self.snapshot.init_restore(manifest.clone(), true) {
warn!("Failed to initialize snapshot restoration: {}", e);
}
} | conditional_block |
service.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any lat... | run_ipc(ipc_path, client.clone(), snapshot.clone(), stop_guard.share());
Ok(ClientService {
io_service: Arc::new(io_service),
client: client,
snapshot: snapshot,
panic_handler: panic_handler,
database: db,
_stop_guard: stop_guard,
})
}
/// Get general IO interface
pub fn register_io_handler... |
let stop_guard = ::devtools::StopGuard::new(); | random_line_split |
call.rs | //! Facilities for working with `v8::FunctionCallbackInfo` and getting the current `v8::Isolate`.
use std::os::raw::c_void;
use std::ptr::null_mut;
use raw::{FunctionCallbackInfo, Isolate, Local};
#[repr(C)]
pub struct | {
pub static_callback: *mut c_void,
pub dynamic_callback: *mut c_void
}
impl Default for CCallback {
fn default() -> Self {
CCallback {
static_callback: null_mut(),
dynamic_callback: null_mut()
}
}
}
extern "C" {
/// Sets the return value of the function c... | CCallback | identifier_name |
call.rs | //! Facilities for working with `v8::FunctionCallbackInfo` and getting the current `v8::Isolate`.
use std::os::raw::c_void;
use std::ptr::null_mut;
use raw::{FunctionCallbackInfo, Isolate, Local};
#[repr(C)]
pub struct CCallback {
pub static_callback: *mut c_void,
pub dynamic_callback: *mut c_void
}
impl Def... | /// Sets the return value of the function call.
#[link_name = "Neon_Call_SetReturn"]
pub fn set_return(info: &FunctionCallbackInfo, value: Local);
/// Gets the isolate of the function call.
#[link_name = "Neon_Call_GetIsolate"]
pub fn get_isolate(info: &FunctionCallbackInfo) -> *mut Isolate;
... |
extern "C" {
| random_line_split |
lib.rs | #![deny(missing_docs)]
//! Bootstrapped meta rules for mathematical notation.
extern crate range;
extern crate piston_meta;
use piston_meta::Syntax;
pub mod interpreter;
/// Gets the syntax rules.
pub fn syntax_rules() -> Syntax {
use piston_meta::*;
let meta_rules = bootstrap::rules();
let source = i... | let _ = load_syntax_data2(syntax, "assets/the-simpsons.txt");
}
} | let _ = load_syntax_data2(syntax, "assets/option.txt");
let _ = load_syntax_data2(syntax, "assets/string.txt"); | random_line_split |
lib.rs | #![deny(missing_docs)]
//! Bootstrapped meta rules for mathematical notation.
extern crate range;
extern crate piston_meta;
use piston_meta::Syntax;
pub mod interpreter;
/// Gets the syntax rules.
pub fn syntax_rules() -> Syntax {
use piston_meta::*;
let meta_rules = bootstrap::rules();
let source = i... | () {
let syntax = "assets/syntax.txt";
let _ = load_syntax_data2(syntax, "assets/bool.txt");
let _ = load_syntax_data2(syntax, "assets/nat.txt");
let _ = load_syntax_data2(syntax, "assets/option.txt");
let _ = load_syntax_data2(syntax, "assets/string.txt");
let _ = load_s... | test_syntax | identifier_name |
lib.rs | #![deny(missing_docs)]
//! Bootstrapped meta rules for mathematical notation.
extern crate range;
extern crate piston_meta;
use piston_meta::Syntax;
pub mod interpreter;
/// Gets the syntax rules.
pub fn syntax_rules() -> Syntax {
use piston_meta::*;
let meta_rules = bootstrap::rules();
let source = i... |
}
| {
let syntax = "assets/syntax.txt";
let _ = load_syntax_data2(syntax, "assets/bool.txt");
let _ = load_syntax_data2(syntax, "assets/nat.txt");
let _ = load_syntax_data2(syntax, "assets/option.txt");
let _ = load_syntax_data2(syntax, "assets/string.txt");
let _ = load_synt... | identifier_body |
day_6.rs | pub fn compress(src: &str) -> String {
let mut compressed = String::new();
let mut chars = src.chars().peekable();
while let Some(c) = chars.peek().cloned() {
let mut counter = 0;
while let Some(n) = chars.peek().cloned() {
if c == n {
counter += 1;
... |
#[test]
fn compress_doubled_chars_string() {
assert_eq!(compress("aabbcc"), "2a2b2c");
}
}
| {
assert_eq!(compress("abc"), "1a1b1c");
} | identifier_body |
day_6.rs | pub fn compress(src: &str) -> String {
let mut compressed = String::new();
let mut chars = src.chars().peekable();
while let Some(c) = chars.peek().cloned() {
let mut counter = 0;
while let Some(n) = chars.peek().cloned() {
if c == n {
counter += 1;
... | #[test]
fn compress_unique_chars_string() {
assert_eq!(compress("abc"), "1a1b1c");
}
#[test]
fn compress_doubled_chars_string() {
assert_eq!(compress("aabbcc"), "2a2b2c");
}
} | random_line_split | |
day_6.rs | pub fn compress(src: &str) -> String {
let mut compressed = String::new();
let mut chars = src.chars().peekable();
while let Some(c) = chars.peek().cloned() {
let mut counter = 0;
while let Some(n) = chars.peek().cloned() {
if c == n {
counter += 1;
... | () {
assert_eq!(compress("aabbcc"), "2a2b2c");
}
}
| compress_doubled_chars_string | identifier_name |
day_6.rs | pub fn compress(src: &str) -> String {
let mut compressed = String::new();
let mut chars = src.chars().peekable();
while let Some(c) = chars.peek().cloned() {
let mut counter = 0;
while let Some(n) = chars.peek().cloned() {
if c == n | else {
break;
}
}
compressed.push_str(counter.to_string().as_str());
compressed.push(c);
}
compressed
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn compress_empty_string() {
assert_eq!(compress(""), "");
}
#[test]
fn c... | {
counter += 1;
chars.next();
} | conditional_block |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
#[macro_use]
extern crate serde;
use euclid::default::{Point2D, Rect, Size2D};
use malloc_size_of_derive::Malloc... |
if origin.y < 0 {
size.height = size.height.saturating_sub(-origin.y as u32);
origin.y = 0;
}
Rect::new(origin.to_u32(), size)
.intersection(&Rect::from_size(surface))
.filter(|rect|!rect.is_empty())
}
| {
size.width = size.width.saturating_sub(-origin.x as u32);
origin.x = 0;
} | conditional_block |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
#[macro_use]
extern crate serde;
use euclid::default::{Point2D, Rect, Size2D};
use malloc_size_of_derive::Malloc... | (pixels: &[u8], size: Size2D<u32>, rect: Rect<u32>) -> Cow<[u8]> {
assert!(!rect.is_empty());
assert!(Rect::from_size(size).contains_rect(&rect));
assert_eq!(pixels.len() % 4, 0);
assert_eq!(size.area() as usize, pixels.len() / 4);
let area = rect.size.area() as usize;
let first_column_start = r... | rgba8_get_rect | identifier_name |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
#[macro_use] | extern crate serde;
use euclid::default::{Point2D, Rect, Size2D};
use malloc_size_of_derive::MallocSizeOf;
use std::borrow::Cow;
#[derive(Clone, Copy, Debug, Deserialize, Eq, MallocSizeOf, PartialEq, Serialize)]
pub enum PixelFormat {
/// Luminance channel only
K8,
/// Luminance + alpha
KA8,
/// R... | random_line_split | |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
#[macro_use]
extern crate serde;
use euclid::default::{Point2D, Rect, Size2D};
use malloc_size_of_derive::Malloc... | {
if origin.x < 0 {
size.width = size.width.saturating_sub(-origin.x as u32);
origin.x = 0;
}
if origin.y < 0 {
size.height = size.height.saturating_sub(-origin.y as u32);
origin.y = 0;
}
Rect::new(origin.to_u32(), size)
.intersection(&Rect::from_size(surface)... | identifier_body | |
vrstageparameters.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use core::nonzero::NonZero;
use dom::bindings::cell::DomRefCell;
use dom::bindings::codegen::Bindings::VRStagePara... |
// https://w3c.github.io/webvr/#dom-vrstageparameters-sizez
fn SizeZ(&self) -> Finite<f32> {
Finite::wrap(self.parameters.borrow().size_z)
}
}
| {
Finite::wrap(self.parameters.borrow().size_x)
} | identifier_body |
vrstageparameters.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use core::nonzero::NonZero;
use dom::bindings::cell::DomRefCell;
use dom::bindings::codegen::Bindings::VRStagePara... | if let Ok(mut array) = array {
array.update(¶meters.sitting_to_standing_transform);
}
}
*self.parameters.borrow_mut() = parameters.clone();
}
}
impl VRStageParametersMethods for VRStageParameters {
#[allow(unsafe_code)]
// https://w3c.github.io/we... | let cx = self.global().get_cx();
typedarray!(in(cx) let array: Float32Array = self.transform.get()); | random_line_split |
vrstageparameters.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use core::nonzero::NonZero;
use dom::bindings::cell::DomRefCell;
use dom::bindings::codegen::Bindings::VRStagePara... |
}
*self.parameters.borrow_mut() = parameters.clone();
}
}
impl VRStageParametersMethods for VRStageParameters {
#[allow(unsafe_code)]
// https://w3c.github.io/webvr/#dom-vrstageparameters-sittingtostandingtransform
unsafe fn SittingToStandingTransform(&self, _cx: *mut JSContext) -> Non... | {
array.update(¶meters.sitting_to_standing_transform);
} | conditional_block |
vrstageparameters.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use core::nonzero::NonZero;
use dom::bindings::cell::DomRefCell;
use dom::bindings::codegen::Bindings::VRStagePara... | {
reflector_: Reflector,
#[ignore_heap_size_of = "Defined in rust-webvr"]
parameters: DomRefCell<WebVRStageParameters>,
transform: Heap<*mut JSObject>,
}
unsafe_no_jsmanaged_fields!(WebVRStageParameters);
impl VRStageParameters {
fn new_inherited(parameters: WebVRStageParameters) -> VRStageParame... | VRStageParameters | identifier_name |
standard.rs |
use super::super::*;
pub const TRANSPARENT: u8 = 0;
pub const PINKISH_TAN: u8 = 1;
pub const ORANGEY_RED: u8 = 2;
pub const ROUGE: u8 = 3;
pub const STRONG_PINK: u8 = 4;
pub const BUBBLEGUM_PINK: u8 = 5;
pub const PINK_PURPLE: u8 = 6;
pub const WARM_PURPLE: u8 = 7;
pub const BURGUNDY: u8 = 8;
pub const NAVY_BLUE: u8 ... | () -> Vec<String> {
vec
use ruma_api::ruma_api;
use serde::{Deserialize, Serialize};
ruma_api! {
metadata {
description: "Gets the homeserver's supported login types to authenticate users. Clients should pick one of t... | () {
assert_eq!(
from_json_value::<LoginType>(json!({ "type": "m.login.password" })).unwrap(),
LoginType::Password,
);
}
}
| deserialize_login_type | identifier_name |
get_login_types.rs | //! [GET /_matrix/client/r0/login](https://matrix.org/docs/spec/client_server/r0.6.0#get-matrix-client-r0-login)
use ruma_api::ruma_api;
use serde::{Deserialize, Serialize};
ruma_api! {
metadata {
description: "Gets the homeserver's supported login types to authenticate users. Clients should pick one of t... | #[serde(rename = "m.login.token")]
Token,
}
#[cfg(test)]
mod tests {
use serde_json::{from_value as from_json_value, json};
use super::LoginType;
#[test]
fn deserialize_login_type() {
assert_eq!(
from_json_value::<LoginType>(json!({ "type": "m.login.password" })).unwrap(),... | random_line_split | |
generics-and-bounds.rs | // build-pass (FIXME(62277): could be check-pass?)
// edition:2018
// compile-flags: --crate-type lib
use std::future::Future;
pub async fn simple_generic<T>() {}
pub trait Foo {
fn foo(&self) {}
}
struct FooType;
impl Foo for FooType {}
pub async fn call_generic_bound<F: Foo>(f: F) {
f.foo()
}
pub async ... | <F: Foo>(f: F) -> impl Future<Output = ()> {
async move { f.foo() }
}
pub fn call_where_clause_block<F>(f: F) -> impl Future<Output = ()>
where
F: Foo,
{
async move { f.foo() }
}
pub fn call_impl_trait_block(f: impl Foo) -> impl Future<Output = ()> {
async move { f.foo() }
}
pub fn call_with_ref_bloc... | call_generic_bound_block | identifier_name |
generics-and-bounds.rs | // build-pass (FIXME(62277): could be check-pass?)
// edition:2018
// compile-flags: --crate-type lib
use std::future::Future;
pub async fn simple_generic<T>() {}
pub trait Foo {
fn foo(&self) {}
}
struct FooType;
impl Foo for FooType {}
pub async fn call_generic_bound<F: Foo>(f: F) {
f.foo()
}
pub async ... | pub async fn call_with_ref(f: &impl Foo) {
f.foo()
}
pub fn async_fn_with_same_generic_params_unifies() {
let mut a = call_generic_bound(FooType);
a = call_generic_bound(FooType);
let mut b = call_where_clause(FooType);
b = call_where_clause(FooType);
let mut c = call_impl_trait(FooType);
... | pub async fn call_impl_trait(f: impl Foo) {
f.foo()
}
| random_line_split |
generics-and-bounds.rs | // build-pass (FIXME(62277): could be check-pass?)
// edition:2018
// compile-flags: --crate-type lib
use std::future::Future;
pub async fn simple_generic<T>() {}
pub trait Foo {
fn foo(&self) {}
}
struct FooType;
impl Foo for FooType {}
pub async fn call_generic_bound<F: Foo>(f: F) {
f.foo()
}
pub async ... |
pub fn async_fn_with_same_generic_params_unifies() {
let mut a = call_generic_bound(FooType);
a = call_generic_bound(FooType);
let mut b = call_where_clause(FooType);
b = call_where_clause(FooType);
let mut c = call_impl_trait(FooType);
c = call_impl_trait(FooType);
let f_one = FooType;... | {
f.foo()
} | identifier_body |
shootout-binarytrees.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
// |
extern mod extra;
use std::iter::range_step;
use extra::future::Future;
use extra::arena::TypedArena;
enum Tree<'a> {
Nil,
Node(&'a Tree<'a>, &'a Tree<'a>, int)
}
fn item_check(t: &Tree) -> int {
match *t {
Nil => 0,
Node(l, r, i) => i + item_check(l) - item_check(r)
}
}
fn bottom_u... | // 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. | random_line_split |
shootout-binarytrees.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | () {
let args = std::os::args();
let n = if std::os::getenv("RUST_BENCH").is_some() {
17
} else if args.len() <= 1u {
8
} else {
from_str(args[1]).unwrap()
};
let min_depth = 4;
let max_depth = if min_depth + 2 > n {min_depth + 2} else {n};
{
let arena = ... | main | identifier_name |
shootout-binarytrees.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... |
fn bottom_up_tree<'r>(arena: &'r TypedArena<Tree<'r>>, item: int, depth: int)
-> &'r Tree<'r> {
if depth > 0 {
arena.alloc(Node(bottom_up_tree(arena, 2 * item - 1, depth - 1),
bottom_up_tree(arena, 2 * item, depth - 1),
item))
} else ... | {
match *t {
Nil => 0,
Node(l, r, i) => i + item_check(l) - item_check(r)
}
} | identifier_body |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#![feature(box_patterns)]
#![feature(box_syntax)]
#![feature(conservative_impl_trait)]
#![feature(nonzero)]
#![fea... | pub mod traversal;
pub mod webrender_helpers;
pub mod wrapper;
// For unit tests:
pub use fragment::Fragment;
pub use fragment::SpecificFragmentInfo; | mod table_rowgroup;
mod table_wrapper;
mod text; | random_line_split |
send_message.rs | use std::borrow::Cow;
use std::ops::Not;
use crate::requests::*;
use crate::types::*;
/// Use this method to send text messages.
#[derive(Debug, Clone, PartialEq, PartialOrd, Serialize)]
#[must_use = "requests do nothing unless sent"]
pub struct SendMessage<'s> {
chat_id: ChatRef,
text: Cow<'s, str>,
#[se... |
}
/// Reply with text message.
pub trait CanReplySendMessage {
fn text_reply<'c,'s, T>(&self, text: T) -> SendMessage<'s>
where
T: Into<Cow<'s, str>>;
}
impl<M> CanReplySendMessage for M
where
M: ToMessageId + ToSourceChat,
{
fn text_reply<'c,'s, T>(&self, text: T) -> SendMessage<'s>
wher... | {
SendMessage::new(self, text)
} | identifier_body |
send_message.rs | use std::borrow::Cow;
use std::ops::Not;
use crate::requests::*;
use crate::types::*;
/// Use this method to send text messages.
#[derive(Debug, Clone, PartialEq, PartialOrd, Serialize)]
#[must_use = "requests do nothing unless sent"]
pub struct SendMessage<'s> {
chat_id: ChatRef,
text: Cow<'s, str>,
#[se... | pub fn new<C, T>(chat: C, text: T) -> Self
where
C: ToChatRef,
T: Into<Cow<'s, str>>,
{
SendMessage {
chat_id: chat.to_chat_ref(),
text: text.into(),
parse_mode: None,
disable_web_page_preview: false,
disable_notification: f... | impl<'s> SendMessage<'s> { | random_line_split |
send_message.rs | use std::borrow::Cow;
use std::ops::Not;
use crate::requests::*;
use crate::types::*;
/// Use this method to send text messages.
#[derive(Debug, Clone, PartialEq, PartialOrd, Serialize)]
#[must_use = "requests do nothing unless sent"]
pub struct SendMessage<'s> {
chat_id: ChatRef,
text: Cow<'s, str>,
#[se... | <'s, T>(&self, text: T) -> SendMessage<'s>
where
T: Into<Cow<'s, str>>,
{
SendMessage::new(self, text)
}
}
/// Reply with text message.
pub trait CanReplySendMessage {
fn text_reply<'c,'s, T>(&self, text: T) -> SendMessage<'s>
where
T: Into<Cow<'s, str>>;
}
impl<M> CanReply... | text | identifier_name |
base.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 std::vec;
use stb_image = stb_image::image;
// FIXME: Images must not be copied every frame. Instead we shoul... |
pub fn test_image_bin() -> ~[u8] {
return vec::from_fn(4962, |i| TEST_IMAGE[i]);
}
pub fn load_from_memory(buffer: &[u8]) -> Option<Image> {
// Can't remember why we do this. Maybe it's what cairo wants
static FORCE_DEPTH: uint = 4;
match stb_image::load_from_memory_with_depth(buffer, FORCE_DEPTH, tr... |
static TEST_IMAGE: [u8, ..4962] = include_bin!("test.jpeg"); | random_line_split |
base.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 std::vec;
use stb_image = stb_image::image;
// FIXME: Images must not be copied every frame. Instead we shoul... |
pub fn load_from_memory(buffer: &[u8]) -> Option<Image> {
// Can't remember why we do this. Maybe it's what cairo wants
static FORCE_DEPTH: uint = 4;
match stb_image::load_from_memory_with_depth(buffer, FORCE_DEPTH, true) {
stb_image::ImageU8(image) => {
assert!(image.depth == 4);
... | {
return vec::from_fn(4962, |i| TEST_IMAGE[i]);
} | identifier_body |
base.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 std::vec;
use stb_image = stb_image::image;
// FIXME: Images must not be copied every frame. Instead we shoul... | () -> ~[u8] {
return vec::from_fn(4962, |i| TEST_IMAGE[i]);
}
pub fn load_from_memory(buffer: &[u8]) -> Option<Image> {
// Can't remember why we do this. Maybe it's what cairo wants
static FORCE_DEPTH: uint = 4;
match stb_image::load_from_memory_with_depth(buffer, FORCE_DEPTH, true) {
stb_imag... | test_image_bin | identifier_name |
types.rs | #[derive(Debug, Clone)]
pub enum FnType {
Simple,
None,
}
impl<'a> Into<String> for &'a FnType {
fn into(self) -> String {
match self {
&FnType::Simple => String::from("SIMPLE"),
_ => String::from(""),
}
}
}
impl Into<String> for FnType {
fn into(self) -> St... | (s: String) -> FnType {
match s.as_ref() {
"SIMPLE" => FnType::Simple,
_ => FnType::None,
}
}
}
impl PartialEq for FnType {
fn eq(&self, st: &FnType) -> bool {
let s: String = self.into();
let o: String = st.into();
s == o
}
}
#[derive(Debug,... | from | identifier_name |
types.rs | #[derive(Debug, Clone)]
pub enum FnType {
Simple,
None,
}
impl<'a> Into<String> for &'a FnType {
fn into(self) -> String {
match self { | }
impl Into<String> for FnType {
fn into(self) -> String {
(&self).into()
}
}
impl From<String> for FnType {
fn from(s: String) -> FnType {
match s.as_ref() {
"SIMPLE" => FnType::Simple,
_ => FnType::None,
}
}
}
impl PartialEq for FnType {
fn eq(&se... | &FnType::Simple => String::from("SIMPLE"),
_ => String::from(""),
}
} | random_line_split |
mpw_v3.rs | extern crate ring;
/*
* This file is part of Master Password.
*
* Master Password is free software: you can redistribute it and/or modify
* Mit 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 versio... |
#[test]
fn get_master_password() {
let master_key = master_key("test", "pass", &SiteVariant::Password).unwrap();
let actual = password_for_site(&master_key,
"site",
&SiteType::Maximum,
... | {
let actual = master_key("test", "pass", &SiteVariant::Password)
.unwrap()
.to_vec();
assert_eq!(actual,
vec![51, 253, 82, 252, 68, 97, 191, 162, 127, 73, 153, 160, 52, 128, 204, 4, 183,
190, 106, 180, 68, 126, 100, 94, 132, 141, 99, 1... | identifier_body |
mpw_v3.rs | extern crate ring;
/*
* This file is part of Master Password.
*
* Master Password is free software: you can redistribute it and/or modify
* Mit 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 versio... | () {
let master_key = master_key("test", "pass", &SiteVariant::Password).unwrap();
let actual = password_for_site(&master_key,
"site",
&SiteType::Maximum,
&(1 as i32),
... | get_master_password | identifier_name |
mpw_v3.rs | extern crate ring;
/*
* This file is part of Master Password.
*
* Master Password is free software: you can redistribute it and/or modify
* Mit 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 versio... | use common;
use common::{SiteVariant, SiteType};
pub fn master_key(full_name: &str,
master_password: &str,
site_variant: &SiteVariant)
-> Option<[u8; common::KEY_LENGTH]> {
let scope = common::scope_for_variant(site_variant);
if scope.is_some() {
l... | * You should have received a copy of the GNU General Public License
* along with Master Password. If not, see <http://www.gnu.org/licenses/>.
*/
use self::ring::{digest, hmac}; | random_line_split |
mpw_v3.rs | extern crate ring;
/*
* This file is part of Master Password.
*
* Master Password is free software: you can redistribute it and/or modify
* Mit 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 versio... | else {
Some(String::from_utf8(password.iter().map(|c| c.unwrap()).collect::<Vec<u8>>())
.unwrap())
}
} else {
None
}
} else {
None
}
}
#[cfg(test)]
mod tests {
use super::*;
use common::{SiteType, SiteVariant};
#[t... | {
None
} | conditional_block |
compiletest.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | <'a>(maybestr: &'a Option<String>) -> &'a str {
match *maybestr {
None => "(none)",
Some(ref s) => s,
}
}
pub fn opt_str2(maybestr: Option<String>) -> String {
match maybestr {
None => "(none)".to_string(),
Some(s) => s,
}
}
pub fn run_tests(config: &Config) {
if co... | opt_str | identifier_name |
compiletest.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... |
test::DynTestName(format!("[{}] {}", config.mode, shorten(testfile)))
}
pub fn make_test_closure(config: &Config, testfile: &Path) -> test::TestFn {
let config = (*config).clone();
// FIXME (#9639): This needs to handle non-utf8 paths
let testfile = testfile.as_str().unwrap().to_string();
test::D... | {
let filename = path.filename_str();
let p = path.dir_path();
let dir = p.filename_str();
format!("{}/{}", dir.unwrap_or(""), filename.unwrap_or(""))
} | identifier_body |
compiletest.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | },
_ => None
}
}
fn extract_lldb_version(full_version_line: Option<String>) -> Option<String> {
// Extract the major LLDB version from the given version string.
// LLDB version strings are different for Apple and non-Apple platforms.
// At the moment, this function only supports the App... | full_version_line);
None | random_line_split |
bit_distributor.rs | use num::basic::integers::PrimitiveInt;
use num::logic::traits::{BitConvertible, NotAssign};
use std::fmt::Debug;
const COUNTER_WIDTH: usize = u64::WIDTH as usize;
/// This struct is used to configure `BitDistributor`s.
///
/// See the `BitDistributor` documentation for more.
#[derive(Clone, Copy, Debug, Eq, Hash, Pa... | /// if `max_bits` wasn't specified, but will stop growing once it reaches $2^b-1$.
#[derive(Clone, Debug, Eq, PartialEq, Hash)]
pub struct BitDistributor {
pub output_types: Vec<BitDistributorOutputType>,
bit_map: [usize; COUNTER_WIDTH],
counter: [bool; COUNTER_WIDTH],
}
impl BitDistributor {
fn new_wi... | /// type. But if `max_bits` is set to $b$, then the corresponding element will start growing just as | random_line_split |
bit_distributor.rs | use num::basic::integers::PrimitiveInt;
use num::logic::traits::{BitConvertible, NotAssign};
use std::fmt::Debug;
const COUNTER_WIDTH: usize = u64::WIDTH as usize;
/// This struct is used to configure `BitDistributor`s.
///
/// See the `BitDistributor` documentation for more.
#[derive(Clone, Copy, Debug, Eq, Hash, Pa... | else {
ni -= 1;
}
weight_counter = self.output_types[normal_output_type_indices[ni]].weight;
}
} else {
if tiny_output_type_indices.is_empty() {
self.bit_map[i] = usize::MAX;
... | {
ni = normal_output_type_indices.len() - 1;
} | conditional_block |
bit_distributor.rs | use num::basic::integers::PrimitiveInt;
use num::logic::traits::{BitConvertible, NotAssign};
use std::fmt::Debug;
const COUNTER_WIDTH: usize = u64::WIDTH as usize;
/// This struct is used to configure `BitDistributor`s.
///
/// See the `BitDistributor` documentation for more.
#[derive(Clone, Copy, Debug, Eq, Hash, Pa... |
fn update_bit_map(&mut self) {
let (mut normal_output_type_indices, mut tiny_output_type_indices): (
Vec<usize>,
Vec<usize>,
) = (0..self.output_types.len()).partition(|&i| self.output_types[i].weight!= 0);
let mut normal_output_types_bits_used = vec![0; normal_outp... | {
self.bit_map.as_ref()
} | identifier_body |
bit_distributor.rs | use num::basic::integers::PrimitiveInt;
use num::logic::traits::{BitConvertible, NotAssign};
use std::fmt::Debug;
const COUNTER_WIDTH: usize = u64::WIDTH as usize;
/// This struct is used to configure `BitDistributor`s.
///
/// See the `BitDistributor` documentation for more.
#[derive(Clone, Copy, Debug, Eq, Hash, Pa... | (&mut self, output_type_indices: &[usize], max_bits: usize) {
assert_ne!(max_bits, 0);
for &index in output_type_indices {
self.output_types[index].max_bits = Some(max_bits);
}
self.update_bit_map();
}
/// Increments the counter in preparation for a new set of output... | set_max_bits | identifier_name |
custom_build.rs | use std::collections::{HashMap, BTreeSet, HashSet};
use std::fs;
use std::path::{PathBuf, Path};
use std::str;
use std::sync::{Mutex, Arc};
use core::PackageId;
use util::{CargoResult, Human};
use util::{internal, ChainError, profile, paths};
use util::Freshness;
use super::job::Work;
use super::{fingerprint, Kind, C... | }
fn build_work<'a, 'cfg>(cx: &mut Context<'a, 'cfg>, unit: &Unit<'a>)
-> CargoResult<(Work, Work)> {
let (script_output, build_output) = {
(cx.layout(unit.pkg, Kind::Host).build(unit.pkg),
cx.layout(unit.pkg, unit.kind).build_out(unit.pkg))
};
// Building the comm... |
Ok((work_dirty.then(dirty), work_fresh.then(fresh), freshness)) | random_line_split |
custom_build.rs | use std::collections::{HashMap, BTreeSet, HashSet};
use std::fs;
use std::path::{PathBuf, Path};
use std::str;
use std::sync::{Mutex, Arc};
use core::PackageId;
use util::{CargoResult, Human};
use util::{internal, ChainError, profile, paths};
use util::Freshness;
use super::job::Work;
use super::{fingerprint, Kind, C... | (path: &Path, pkg_name: &str) -> CargoResult<BuildOutput> {
let contents = try!(paths::read_bytes(path));
BuildOutput::parse(&contents, pkg_name)
}
// Parses the output of a script.
// The `pkg_name` is used for error messages.
pub fn parse(input: &[u8], pkg_name: &str) -> CargoResult<B... | parse_file | identifier_name |
script_msg.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 https://mozilla.org/MPL/2.0/. */
use crate::AnimationState;
use crate::AuxiliaryBrowsingContextLoadInfo;
use crate::BroadcastMsg;
use crate::Docum... | /// Data representing a serviceworker registration.
Registration {
/// The Id of the registration.
id: ServiceWorkerRegistrationId,
/// The installing worker, if any.
installing_worker: Option<ServiceWorkerId>,
/// The waiting worker, if any.
waiting_worker: Optio... | pub enum JobResultValue { | random_line_split |
script_msg.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 https://mozilla.org/MPL/2.0/. */
use crate::AnimationState;
use crate::AuxiliaryBrowsingContextLoadInfo;
use crate::BroadcastMsg;
use crate::Docum... | ChangeRunningAnimationsState(..) => "ChangeRunningAnimationsState",
CreateCanvasPaintThread(..) => "CreateCanvasPaintThread",
Focus => "Focus",
GetBrowsingContextInfo(..) => "GetBrowsingContextInfo",
GetTopForBrowsingContext(..) => "GetParentBrowsingContext",
... | {
use self::ScriptMsg::*;
let variant = match *self {
CompleteMessagePortTransfer(..) => "CompleteMessagePortTransfer",
MessagePortTransferResult(..) => "MessagePortTransferResult",
NewMessagePortRouter(..) => "NewMessagePortRouter",
RemoveMessagePortRoute... | identifier_body |
script_msg.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 https://mozilla.org/MPL/2.0/. */
use crate::AnimationState;
use crate::AuxiliaryBrowsingContextLoadInfo;
use crate::BroadcastMsg;
use crate::Docum... | {
/// Request to complete the transfer of a set of ports to a router.
CompleteMessagePortTransfer(MessagePortRouterId, Vec<MessagePortId>),
/// The results of attempting to complete the transfer of a batch of ports.
MessagePortTransferResult(
/* The router whose transfer of ports succeeded, if ... | ScriptMsg | identifier_name |
issue-64655-allow-unwind-when-calling-panic-directly.rs | // run-pass
// ignore-wasm32-bare compiled with panic=abort by default
// ignore-emscripten no threads support
// rust-lang/rust#64655: with panic=unwind, a panic from a subroutine
// should still run destructors as it unwinds the stack. However,
// bugs with how the nounwind LLVM attribute was applied led to this
// ... | ;
impl Drop for Droppable {
fn drop(&mut self) {
SHARED.fetch_add(1, Ordering::SeqCst);
}
}
let _guard = Droppable;
core::panicking::panic("???");
});
let wait = handle.join();
// Reinstate handler to ease observation of assertion fa... | Droppable | identifier_name |
issue-64655-allow-unwind-when-calling-panic-directly.rs | // run-pass
// ignore-wasm32-bare compiled with panic=abort by default
// ignore-emscripten no threads support
// rust-lang/rust#64655: with panic=unwind, a panic from a subroutine
// should still run destructors as it unwinds the stack. However,
// bugs with how the nounwind LLVM attribute was applied led to this
// ... | SHARED.fetch_add(1, Ordering::SeqCst);
}
}
let _guard = Droppable;
core::panicking::panic("???");
});
let wait = handle.join();
// Reinstate handler to ease observation of assertion failures.
std::panic::set_hook(old_hook);
assert!(wait.is_err(... | let handle = std::thread::spawn(|| {
struct Droppable;
impl Drop for Droppable {
fn drop(&mut self) { | random_line_split |
login.rs | use std::io;
use cargo::ops;
use cargo::core::{MultiShell, SourceId, Source};
use cargo::sources::RegistrySource;
use cargo::util::{CliResult, CliError, Config};
#[derive(RustcDecodable)]
struct Options {
flag_host: Option<String>,
arg_token: Option<String>,
flag_verbose: bool,
}
pub const USAGE: &'stati... | ";
pub fn execute(options: Options, shell: &mut MultiShell) -> CliResult<Option<()>> {
shell.set_verbose(options.flag_verbose);
let token = match options.arg_token.clone() {
Some(token) => token,
None => {
let err = (|:| {
let config = try!(Config::new(shell, None, N... | -h, --help Print this message
--host HOST Host to set the token for
-v, --verbose Use verbose output
| random_line_split |
login.rs | use std::io;
use cargo::ops;
use cargo::core::{MultiShell, SourceId, Source};
use cargo::sources::RegistrySource;
use cargo::util::{CliResult, CliError, Config};
#[derive(RustcDecodable)]
struct | {
flag_host: Option<String>,
arg_token: Option<String>,
flag_verbose: bool,
}
pub const USAGE: &'static str = "
Save an api token from the registry locally
Usage:
cargo login [options] [<token>]
Options:
-h, --help Print this message
--host HOST Host to set the token... | Options | identifier_name |
structured_errors.rs | // Copyright 2018 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 common(&self) -> DiagnosticBuilder<'tcx> {
if self.expr_ty.references_error() {
self.sess.diagnostic().struct_dummy()
} else {
self.sess.struct_span_fatal_with_code(
self.span,
&format!("cannot cast thin pointer `{}` to fat pointer `{}`",
... | {
__diagnostic_used!(E0607);
DiagnosticId::Error("E0607".to_owned())
} | identifier_body |
structured_errors.rs | // Copyright 2018 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 ... | (sess: &'tcx Session,
span: Span,
expr_ty: Ty<'tcx>,
cast_ty: String) -> SizedUnsizedCastError<'tcx> {
SizedUnsizedCastError { sess, span, expr_ty, cast_ty }
}
}
impl<'tcx> StructuredDiagnostic<'tcx> for SizedUnsizedCastError<'tcx> {
fn session(&self) -> &Se... | new | identifier_name |
structured_errors.rs | // Copyright 2018 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 ... |
err
}
fn extended(&self, mut err: DiagnosticBuilder<'tcx>) -> DiagnosticBuilder<'tcx> {
err.note(&format!("certain types, like `{}`, must be cast before passing them to a \
variadic function, because of arcane ABI rules dictated by the C \
... | {
err.help(&format!("cast the value to `{}`", self.cast_ty));
} | conditional_block |
structured_errors.rs | // Copyright 2018 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<'tcx> StructuredDiagnostic<'tcx> for SizedUnsizedCastError<'tcx> {
fn session(&self) -> &Session { self.sess }
fn code(&self) -> DiagnosticId {
__diagnostic_used!(E0607);
DiagnosticId::Error("E0607".to_owned())
}
fn common(&self) -> DiagnosticBuilder<'tcx> {
if se... | random_line_split | |
epoll.rs | use nix::fcntl::Fd;
use nix::sys::epoll::*;
use nix::unistd::close;
use io;
use os::event::{IoEvent, Interest, PollOpt};
pub struct Selector {
epfd: Fd
}
impl Selector {
pub fn new() -> io::Result<Selector> {
let epfd = try!(epoll_create().map_err(io::from_nix_error));
Ok(Selector { epfd: epf... | Ok(())
}
/// Register event interests for the given IO handle with the OS
pub fn register(&mut self, fd: Fd, token: usize, interests: Interest, opts: PollOpt) -> io::Result<()> {
let info = EpollEvent {
events: ioevent_to_epoll(interests, opts),
data: token as u64
... | let cnt = try!(epoll_wait(self.epfd, dst, timeout_ms)
.map_err(io::from_nix_error));
unsafe { evts.events.set_len(cnt); }
| random_line_split |
epoll.rs | use nix::fcntl::Fd;
use nix::sys::epoll::*;
use nix::unistd::close;
use io;
use os::event::{IoEvent, Interest, PollOpt};
pub struct | {
epfd: Fd
}
impl Selector {
pub fn new() -> io::Result<Selector> {
let epfd = try!(epoll_create().map_err(io::from_nix_error));
Ok(Selector { epfd: epfd })
}
/// Wait for events from the OS
pub fn select(&mut self, evts: &mut Events, timeout_ms: usize) -> io::Result<()> {
... | Selector | identifier_name |
epoll.rs | use nix::fcntl::Fd;
use nix::sys::epoll::*;
use nix::unistd::close;
use io;
use os::event::{IoEvent, Interest, PollOpt};
pub struct Selector {
epfd: Fd
}
impl Selector {
pub fn new() -> io::Result<Selector> {
let epfd = try!(epoll_create().map_err(io::from_nix_error));
Ok(Selector { epfd: epf... |
if interest.is_hup() {
kind.insert(EPOLLRDHUP);
}
if opts.is_edge() {
kind.insert(EPOLLET);
}
if opts.is_oneshot() {
kind.insert(EPOLLONESHOT);
}
if opts.is_level() {
kind.remove(EPOLLET);
}
kind
}
impl Drop for Selector {
fn drop(&mut self)... | {
kind.insert(EPOLLOUT);
} | conditional_block |
math.rs | use std::mem;
pub use vecmath::{
Vector3,
Matrix4,
vec3_add,
vec3_sub,
vec3_scale,
row_mat4_mul,
row_mat4_transform,
mat4_transposed,
mat4_inv,
mat4_id,
};
pub use quaternion::id as quaternion_id;
pub use quaternion::mul as quaternion_mul;
pub use quaternion::conj as quaternion... |
if m[2][2] > m[i][i] {
i = 2;
}
let j = next[i];
let k = next[j];
let t = (m[i][i] - (m[j][j] + m[k][k])) + 1.0;
let s = inv_sqrt(t) * 0.5;
q[i] = s * t;
q[3] = (m[j][k] - m[k][j]) * s;
q[j] = (m[i][j] + m[j][i]) * s;
q[k] ... | {
i = 1;
} | conditional_block |
math.rs | use std::mem;
pub use vecmath::{
Vector3,
Matrix4,
vec3_add,
vec3_sub,
vec3_scale,
row_mat4_mul,
row_mat4_transform,
mat4_transposed,
mat4_inv,
mat4_id,
};
pub use quaternion::id as quaternion_id;
pub use quaternion::mul as quaternion_mul;
pub use quaternion::conj as quaternion... |
/// Dual-quaternion linear blending. See http://dcgi.felk.cvut.cz/home/zara/papers/TCD-CS-2006-46.pdf
pub fn lerp_dual_quaternion(q1: DualQuaternion<f32>, q2: DualQuaternion<f32>, blend_factor: f32) -> DualQuaternion<f32> {
let dot = dual_quaternion::dot(q1, q2);
let s = 1.0 - blend_factor;
let t: f32 = ... | {
let dot = q1.0 * q2.0 + q1.1[0] * q2.1[0] + q1.1[1] * q2.1[1] + q1.1[2] * q2.1[2];
let s = 1.0 - blend_factor;
let t: f32 = if dot > 0.0 { *blend_factor } else { -blend_factor };
let w = s * q1.0 + t * q2.0;
let x = s * q1.1[0] + t * q2.1[0];
let y = s * q1.1[1] + t * q2.1[1];
let z = s... | identifier_body |
math.rs | use std::mem;
pub use vecmath::{
Vector3,
Matrix4,
vec3_add,
vec3_sub,
vec3_scale,
row_mat4_mul,
row_mat4_transform,
mat4_transposed,
mat4_inv,
mat4_id,
};
pub use quaternion::id as quaternion_id;
pub use quaternion::mul as quaternion_mul;
pub use quaternion::conj as quaternion... | let mut i: i32 = unsafe { mem::transmute(y) };
i = 0x5f3759df - (i >> 1);
y = unsafe { mem::transmute(i) };
y = y * (1.5 - (x2 * y * y));
y
} | pub fn inv_sqrt(x: f32) -> f32 {
let x2: f32 = x * 0.5;
let mut y: f32 = x;
| random_line_split |
math.rs | use std::mem;
pub use vecmath::{
Vector3,
Matrix4,
vec3_add,
vec3_sub,
vec3_scale,
row_mat4_mul,
row_mat4_transform,
mat4_transposed,
mat4_inv,
mat4_id,
};
pub use quaternion::id as quaternion_id;
pub use quaternion::mul as quaternion_mul;
pub use quaternion::conj as quaternion... | (q1: &Quaternion<f32>, q2: &Quaternion<f32>, blend_factor: &f32) -> Quaternion<f32> {
let dot = q1.0 * q2.0 + q1.1[0] * q2.1[0] + q1.1[1] * q2.1[1] + q1.1[2] * q2.1[2];
let s = 1.0 - blend_factor;
let t: f32 = if dot > 0.0 { *blend_factor } else { -blend_factor };
let w = s * q1.0 + t * q2.0;
let... | lerp_quaternion | identifier_name |
msg_filterload.rs | use std;
use ::serialize::{self, Serializable};
#[derive(Debug,Default,Clone)]
pub struct FilterLoadMessage {
pub data: Vec<u8>,
pub hash_funcs: u32,
pub tweak: u32,
pub flags: u8,
}
impl super::Message for FilterLoadMessage {
fn get_command(&self) -> [u8; super::message_header::COMMAND_SIZE] {
su... | (&mut self, io:&mut std::io::Read, ser:&serialize::SerializeParam) -> serialize::Result {
let mut r:usize = 0;
r += try!(self.data.deserialize(io,ser));
r += try!(self.hash_funcs.deserialize(io,ser));
r += try!(self.tweak.deserialize(io,ser));
r += try!(self.flags.deserialize(io,ser));
... | deserialize | identifier_name |
msg_filterload.rs | use std;
use ::serialize::{self, Serializable};
#[derive(Debug,Default,Clone)]
pub struct FilterLoadMessage {
pub data: Vec<u8>,
pub hash_funcs: u32,
pub tweak: u32,
pub flags: u8,
}
impl super::Message for FilterLoadMessage {
fn get_command(&self) -> [u8; super::message_header::COMMAND_SIZE] {
su... | let mut r:usize = 0;
r += try!(self.data.serialize(io,ser));
r += try!(self.hash_funcs.serialize(io,ser));
r += try!(self.tweak.serialize(io,ser));
r += try!(self.flags.serialize(io,ser));
Ok(r)
}
fn deserialize(&mut self, io:&mut std::io::Read, ser:&serialize::SerializeParam) ... | random_line_split | |
sender.rs | extern crate knock;
use std::process;
use Request;
use errors;
use self::knock::*;
use std::fs::File;
use std::io::Write;
use self::knock::response::Response;
pub fn send(request: self::Request, path: &str) {
let mut http = match HTTP::new(&request.url) {
Ok(http) => http,
Err(_) => {
... |
fn save_to_file(response: &Response, path: &str) {
let mut file = match File::create(path) {
Ok(file) => file,
Err(_) => {
errors::invalid_save_path();
process::exit(0);
}
};
let content = response.as_str();
match file.write_all(content.as_bytes()) {
... | {
println!("Status: {}\r\n", response.status);
for (key, val) in response.header.iter() {
println!("{}: {}", key, val);
}
println!("\r\n\r\n{}", response.body);
} | identifier_body |
sender.rs | extern crate knock;
use std::process;
use Request;
use errors;
use self::knock::*;
use std::fs::File;
use std::io::Write;
use self::knock::response::Response;
pub fn send(request: self::Request, path: &str) {
let mut http = match HTTP::new(&request.url) {
Ok(http) => http,
Err(_) => {
... | for (key, val) in response.header.iter() {
println!("{}: {}", key, val);
}
println!("\r\n\r\n{}", response.body);
}
fn save_to_file(response: &Response, path: &str) {
let mut file = match File::create(path) {
Ok(file) => file,
Err(_) => {
errors::invalid_save_path()... |
fn print_response(response: &Response) {
println!("Status: {}\r\n", response.status);
| random_line_split |
sender.rs | extern crate knock;
use std::process;
use Request;
use errors;
use self::knock::*;
use std::fs::File;
use std::io::Write;
use self::knock::response::Response;
pub fn send(request: self::Request, path: &str) {
let mut http = match HTTP::new(&request.url) {
Ok(http) => http,
Err(_) => {
... | (response: &Response, path: &str) {
let mut file = match File::create(path) {
Ok(file) => file,
Err(_) => {
errors::invalid_save_path();
process::exit(0);
}
};
let content = response.as_str();
match file.write_all(content.as_bytes()) {
Ok(_) => p... | save_to_file | identifier_name |
sender.rs | extern crate knock;
use std::process;
use Request;
use errors;
use self::knock::*;
use std::fs::File;
use std::io::Write;
use self::knock::response::Response;
pub fn send(request: self::Request, path: &str) {
let mut http = match HTTP::new(&request.url) {
Ok(http) => http,
Err(_) => {
... |
}
Err(_) => {
errors::invalid_response();
process::exit(0);
}
}
}
fn print_response(response: &Response) {
println!("Status: {}\r\n", response.status);
for (key, val) in response.header.iter() {
println!("{}: {}", key, val);
}
println!("\r\... | {
save_to_file(&response, path);
} | conditional_block |
main.rs | fn main() {
println!("Hello, world!");
let x = 5;
let y = 8;
let z = &y;
if *z == y |
let mut i: i32 = 1;
// foo(&mut i);//error: cannot borrow immutable borrowed content `*z` as mutable
let z=&mut i;
foo(z);//error: cannot borrow immutable borrowed content `*z` as mutable
println!("{} {}",*z,z);
//reference:
let x = 5;
let y = &x;
println!("{}", *y);
print... | {
println!("{:p} {} {}",z,*z, z);
} | conditional_block |
main.rs | fn main() {
println!("Hello, world!");
let x = 5;
let y = 8;
let z = &y;
if *z == y {
println!("{:p} {} {}",z,*z, z);
}
let mut i: i32 = 1;
// foo(&mut i);//error: cannot borrow immutable borrowed content `*z` as mutable
let z=&mut i;
foo(z);//error: cannot borrow imm... | println!("{}", succ(&*x));
println!("{}", succ(&*x));
println!("{}", succ(&*x));
//recursive data structure
let list: List<i32> = List::Cons(1, Box::new(List::Cons(2, Box::new(List::Cons(3, Box::new(List::Nil))))));
println!("{:?}", list);
let x = &mut 5;
if *x < 10 {
let y = ... |
//boxes:
let x = Box::new(5);//Boxes are appropriate to use in two situations: Recursive data structures, and occasionally, when returning data. | random_line_split |
main.rs | fn | () {
println!("Hello, world!");
let x = 5;
let y = 8;
let z = &y;
if *z == y {
println!("{:p} {} {}",z,*z, z);
}
let mut i: i32 = 1;
// foo(&mut i);//error: cannot borrow immutable borrowed content `*z` as mutable
let z=&mut i;
foo(z);//error: cannot borrow immutable ... | main | identifier_name |
main.rs | fn main() {
println!("Hello, world!");
let x = 5;
let y = 8;
let z = &y;
if *z == y {
println!("{:p} {} {}",z,*z, z);
}
let mut i: i32 = 1;
// foo(&mut i);//error: cannot borrow immutable borrowed content `*z` as mutable
let z=&mut i;
foo(z);//error: cannot borrow imm... | { x + 1 } | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.