file_name
large_stringlengths
4
69
prefix
large_stringlengths
0
26.7k
suffix
large_stringlengths
0
24.8k
middle
large_stringlengths
0
2.12k
fim_type
large_stringclasses
4 values
mod.rs
use actix_web::{web::{route, scope, Query}, HttpRequest, Result, Scope}; use actix_web::http::StatusCode; use crate::messages::*; use std::collections::HashMap; pub mod format_msg; mod callback; mod not_understood; pub use self::format_msg::FormatMsg; use self::callback::callback; use self::not_understood::not_unders...
, }; let van = str::from_utf8(array).unwrap(); serde_json::from_str(van).unwrap() } }
{}
conditional_block
mod.rs
use actix_web::{web::{route, scope, Query}, HttpRequest, Result, Scope}; use actix_web::http::StatusCode; use crate::messages::*; use std::collections::HashMap; pub mod format_msg; mod callback; mod not_understood; pub use self::format_msg::FormatMsg; use self::callback::callback; use self::not_understood::not_unders...
() { // Arrange let req = TestRequest::with_uri("/api/404").to_request(); let scope = get_scope(); let mut srv = init_service(App::new().service(scope)); // Act let resp = &block_on(srv.call(req)).unwrap(); // Assert assert_eq!(resp.status(), StatusCode:...
test_get_scope_not_understood
identifier_name
mod.rs
use actix_web::{web::{route, scope, Query}, HttpRequest, Result, Scope}; use actix_web::http::StatusCode; use crate::messages::*; use std::collections::HashMap; pub mod format_msg; mod callback; mod not_understood; pub use self::format_msg::FormatMsg; use self::callback::callback; use self::not_understood::not_unders...
#[test] fn test_get_scope_blank() { // Arrange let req = TestRequest::with_uri("/").to_request(); let scope = get_scope(); let mut srv = init_service(App::new().service(scope)); // Act let resp = block_on(srv.call(req)).unwrap(); // Assert asse...
{ // Arrange let req = TestRequest::with_uri("/api/404").to_request(); let scope = get_scope(); let mut srv = init_service(App::new().service(scope)); // Act let resp = &block_on(srv.call(req)).unwrap(); // Assert assert_eq!(resp.status(), StatusCode::NO...
identifier_body
level.rs
#![feature(test)] use byteorder::{LittleEndian as E, ReadBytesExt}; use std::{ fs::File, io::{Read, Seek}, }; const VMC_PATH: &'static str = "/hub/gog/Vangers/game/thechain/fostral/output.vmc"; const SIZE: [usize; 2] = [1 << 11, 1 << 14]; #[bench] fn load_level(bench: &mut test::Bencher)
splay.expand(&buffer[off..off + size as usize], &mut height, &mut meta); } }); }
{ let mut file = File::open(VMC_PATH).unwrap(); let table: Vec<_> = (0..SIZE[1]) .map(|_| { let offset = file.read_i32::<E>().unwrap(); let size = file.read_i16::<E>().unwrap(); (offset, size) }) .collect(); let splay = splay::Splay::new(&mut file...
identifier_body
level.rs
#![feature(test)] use byteorder::{LittleEndian as E, ReadBytesExt}; use std::{ fs::File, io::{Read, Seek}, }; const VMC_PATH: &'static str = "/hub/gog/Vangers/game/thechain/fostral/output.vmc"; const SIZE: [usize; 2] = [1 << 11, 1 << 14]; #[bench] fn load_level(bench: &mut test::Bencher) { let mut file =...
let mut height = vec![0u8; SIZE[0]]; let mut meta = vec![0u8; SIZE[0]]; let data_offset = file.seek(std::io::SeekFrom::Current(0)).unwrap(); let mut buffer = Vec::new(); file.read_to_end(&mut buffer).unwrap(); bench.iter(|| { for &(offset, size) in table[..0x100].iter() { le...
}) .collect(); let splay = splay::Splay::new(&mut file);
random_line_split
level.rs
#![feature(test)] use byteorder::{LittleEndian as E, ReadBytesExt}; use std::{ fs::File, io::{Read, Seek}, }; const VMC_PATH: &'static str = "/hub/gog/Vangers/game/thechain/fostral/output.vmc"; const SIZE: [usize; 2] = [1 << 11, 1 << 14]; #[bench] fn
(bench: &mut test::Bencher) { let mut file = File::open(VMC_PATH).unwrap(); let table: Vec<_> = (0..SIZE[1]) .map(|_| { let offset = file.read_i32::<E>().unwrap(); let size = file.read_i16::<E>().unwrap(); (offset, size) }) .collect(); let splay = s...
load_level
identifier_name
test_legalizer.rs
//! Test command for checking the IL legalizer. //! //! The `test legalizer` test command runs each function through `legalize_function()` and sends //! the result to filecheck. use std::borrow::Cow; use cretonne; use cretonne::ir::Function; use cretonne::print_errors::pretty_error; use cton_reader::TestCommand; use s...
(&self) -> bool { true } fn run(&self, func: Cow<Function>, context: &Context) -> Result<()> { let mut comp_ctx = cretonne::Context::new(); comp_ctx.func = func.into_owned(); let isa = context.isa.expect("legalizer needs an ISA"); comp_ctx.compute_cfg(); comp_ct...
needs_isa
identifier_name
test_legalizer.rs
//! Test command for checking the IL legalizer. //! //! The `test legalizer` test command runs each function through `legalize_function()` and sends //! the result to filecheck. use std::borrow::Cow; use cretonne; use cretonne::ir::Function; use cretonne::print_errors::pretty_error; use cton_reader::TestCommand; use s...
else { Ok(Box::new(TestLegalizer)) } } impl SubTest for TestLegalizer { fn name(&self) -> Cow<str> { Cow::from("legalizer") } fn is_mutating(&self) -> bool { true } fn needs_isa(&self) -> bool { true } fn run(&self, func: Cow<Function>, context: &Cont...
{ Err(format!("No options allowed on {}", parsed)) }
conditional_block
test_legalizer.rs
//! Test command for checking the IL legalizer. //! //! The `test legalizer` test command runs each function through `legalize_function()` and sends //! the result to filecheck. use std::borrow::Cow; use cretonne; use cretonne::ir::Function; use cretonne::print_errors::pretty_error; use cton_reader::TestCommand; use s...
}
random_line_split
htmlobjectelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::attr::Attr; use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::HTMLObjectElementB...
} impl HTMLObjectElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: &Document) -> HTMLObjectElement { HTMLObjectElement { htmlelement: HTMLElement::new_inherited(HTMLElementTypeId::HTMLObjectElement, l...
{ *self.type_id() == EventTargetTypeId::Node( NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLObjectElement))) }
identifier_body
htmlobjectelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::attr::Attr; use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::HTMLObjectElementB...
use std::sync::Arc; use util::str::DOMString; #[dom_struct] pub struct HTMLObjectElement { htmlelement: HTMLElement, image: DOMRefCell<Option<Arc<Image>>>, } impl HTMLObjectElementDerived for EventTarget { fn is_htmlobjectelement(&self) -> bool { *self.type_id() == EventTargetTypeId::N...
use net_traits::image::base::Image;
random_line_split
htmlobjectelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::attr::Attr; use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::HTMLObjectElementB...
(localName: DOMString, prefix: Option<DOMString>, document: &Document) -> Root<HTMLObjectElement> { let element = HTMLObjectElement::new_inherited(localName, prefix, document); Node::reflect_node(box element, document, HTMLObjectElementBinding::Wrap) } } trait ProcessD...
new
identifier_name
users.rs
use failure::format_err; use log::error; use rusqlite::types::ToSql; use serde_derive::{Deserialize, Serialize}; use crate::db::{self, Database}; use crate::errors::*; #[derive(Deserialize, Serialize, Clone)] pub struct UserInfo { pub id: Option<i32>, pub github: String, pub slack: String, pub mute_di...
(username: &str) -> String { format!("@{}", username) } #[cfg(test)] mod tests { use super::*; use tempdir::TempDir; fn new_test() -> (UserConfig, TempDir) { let temp_dir = TempDir::new("users.rs").unwrap(); let db_file = temp_dir.path().join("db.sqlite3"); let db = Database::n...
mention
identifier_name
users.rs
use failure::format_err; use log::error; use rusqlite::types::ToSql; use serde_derive::{Deserialize, Serialize}; use crate::db::{self, Database}; use crate::errors::*; #[derive(Deserialize, Serialize, Clone)] pub struct UserInfo { pub id: Option<i32>, pub github: String, pub slack: String, pub mute_di...
pub fn delete(&mut self, user_id: i32) -> Result<()> { let conn = self.db.connect()?; conn.execute("DELETE from users where id =?1", &[&user_id]) .map_err(|e| format_err!("Error deleting user {}: {}", user_id, e))?; Ok(()) } pub fn slack_user_name(&self, github_name: &...
{ let conn = self.db.connect()?; conn.execute( "UPDATE users set github_name = ?1, slack_name = ?2, mute_direct_messages = ?3 where id = ?4", &[&user.github, &user.slack, &db::to_tinyint(user.mute_direct_messages) as &dyn ToSql, &user.id], ).map_err(|e| format_err!("Error...
identifier_body
users.rs
use failure::format_err; use log::error; use rusqlite::types::ToSql; use serde_derive::{Deserialize, Serialize}; use crate::db::{self, Database}; use crate::errors::*; #[derive(Deserialize, Serialize, Clone)] pub struct UserInfo { pub id: Option<i32>, pub github: String, pub slack: String, pub mute_di...
let mut stmt = conn.prepare( "SELECT id, slack_name, github_name, mute_direct_messages FROM users ORDER BY github_name", )?; let found = stmt.query_map([], |row| { Ok(UserInfo { id: row.get(0)?, slack: row.get(1)?, github: r...
let conn = self.db.connect()?;
random_line_split
mod.rs
mod let_unit_value; mod unit_arg; mod unit_cmp; mod utils; use rustc_hir::{Expr, Stmt}; use rustc_lint::{LateContext, LateLintPass}; use rustc_session::{declare_lint_pass, declare_tool_lint}; declare_clippy_lint! { /// ### What it does /// Checks for binding a unit value. /// /// ### Why is this bad? ...
}
{ unit_cmp::check(cx, expr); unit_arg::check(cx, expr); }
identifier_body
mod.rs
mod let_unit_value; mod unit_arg; mod unit_cmp; mod utils; use rustc_hir::{Expr, Stmt}; use rustc_lint::{LateContext, LateLintPass}; use rustc_session::{declare_lint_pass, declare_tool_lint}; declare_clippy_lint! { /// ### What it does /// Checks for binding a unit value. /// /// ### Why is this bad? ...
(&mut self, cx: &LateContext<'_>, expr: &Expr<'_>) { unit_cmp::check(cx, expr); unit_arg::check(cx, expr); } }
check_expr
identifier_name
mod.rs
mod let_unit_value; mod unit_arg; mod unit_cmp; mod utils; use rustc_hir::{Expr, Stmt}; use rustc_lint::{LateContext, LateLintPass}; use rustc_session::{declare_lint_pass, declare_tool_lint}; declare_clippy_lint! { /// ### What it does /// Checks for binding a unit value. /// /// ### Why is this bad? ...
/// } { /// baz(); /// } /// ``` /// is equal to /// ```rust /// # fn foo() {}; /// # fn bar() {}; /// # fn baz() {}; /// { /// foo(); /// bar(); /// baz(); /// } /// ``` /// /// For asserts: /// ```rust /// # fn foo() {}; /...
/// bar();
random_line_split
expect-infer-supply-two-infers.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 ...
{ }
identifier_body
expect-infer-supply-two-infers.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 ...
fn expect_free_supply_free<'x>(x: &'x u32) { with_closure(|mut x: Vec<_>, y| { // Shows that the call to `x.push()` is influencing type of `y`... x.push(22_u32); //...since we now know the type of `y` and can resolve the method call. y.wrapping_add(1); }); } fn main() { }
where F: FnOnce(Vec<A>, A) { }
random_line_split
expect-infer-supply-two-infers.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 ...
<'x>(x: &'x u32) { with_closure(|mut x: Vec<_>, y| { // Shows that the call to `x.push()` is influencing type of `y`... x.push(22_u32); //...since we now know the type of `y` and can resolve the method call. y.wrapping_add(1); }); } fn main() { }
expect_free_supply_free
identifier_name
b.rs
// Automatically generated rust module for 'data_types_import.proto' file #![allow(non_snake_case)] #![allow(non_upper_case_globals)] #![allow(non_camel_case_types)] #![allow(unused_imports)] #![allow(unknown_lints)] #![allow(clippy::all)] #![cfg_attr(rustfmt, rustfmt_skip)] use quick_protobuf::{MessageInfo, Message...
(&self) -> usize { 0 + self.i.as_ref().map_or(0, |m| 1 + sizeof_varint(*(m) as u64)) } fn write_message<W: WriterBackend>(&self, w: &mut Writer<W>) -> Result<()> { if let Some(ref s) = self.i { w.write_with_tag(8, |w| w.write_bool(*s))?; } Ok(()) } }
get_size
identifier_name
b.rs
// Automatically generated rust module for 'data_types_import.proto' file #![allow(non_snake_case)] #![allow(non_upper_case_globals)] #![allow(non_camel_case_types)]
#![allow(clippy::all)] #![cfg_attr(rustfmt, rustfmt_skip)] use quick_protobuf::{MessageInfo, MessageRead, MessageWrite, BytesReader, Writer, WriterBackend, Result}; use quick_protobuf::sizeofs::*; use super::super::*; #[derive(Debug, Default, PartialEq, Clone)] pub struct ImportedMessage { pub i: Option<bool>, }...
#![allow(unused_imports)] #![allow(unknown_lints)]
random_line_split
b.rs
// Automatically generated rust module for 'data_types_import.proto' file #![allow(non_snake_case)] #![allow(non_upper_case_globals)] #![allow(non_camel_case_types)] #![allow(unused_imports)] #![allow(unknown_lints)] #![allow(clippy::all)] #![cfg_attr(rustfmt, rustfmt_skip)] use quick_protobuf::{MessageInfo, Message...
fn write_message<W: WriterBackend>(&self, w: &mut Writer<W>) -> Result<()> { if let Some(ref s) = self.i { w.write_with_tag(8, |w| w.write_bool(*s))?; } Ok(()) } }
{ 0 + self.i.as_ref().map_or(0, |m| 1 + sizeof_varint(*(m) as u64)) }
identifier_body
niche.rs
// run-pass //! Make sure that we read and write enum discriminants correctly for corner cases caused //! by layout optimizations. const OVERFLOW: usize = { // Tests for https://github.com/rust-lang/rust/issues/62138. #[repr(u8)] #[allow(dead_code)] enum WithWraparoundInvalidValues { X = 1, ...
{ assert_eq!(OVERFLOW, 0); assert_eq!(MORE_OVERFLOW, 0); }
identifier_body
niche.rs
// run-pass //! Make sure that we read and write enum discriminants correctly for corner cases caused //! by layout optimizations. const OVERFLOW: usize = { // Tests for https://github.com/rust-lang/rust/issues/62138. #[repr(u8)] #[allow(dead_code)] enum WithWraparoundInvalidValues { X = 1, ...
0 }; fn main() { assert_eq!(OVERFLOW, 0); assert_eq!(MORE_OVERFLOW, 0); }
random_line_split
niche.rs
// run-pass //! Make sure that we read and write enum discriminants correctly for corner cases caused //! by layout optimizations. const OVERFLOW: usize = { // Tests for https://github.com/rust-lang/rust/issues/62138. #[repr(u8)] #[allow(dead_code)] enum WithWraparoundInvalidValues { X = 1, ...
if let E2::V1 {.. } = E2::V3::<Infallible> { unreachable!() } if let E2::V3 {.. } = E2::V3::<Infallible> { } else { unreachable!() } 0 }; fn main() { assert_eq!(OVERFLOW, 0); assert_eq!(MORE_OVERFLOW, 0); }
{ unreachable!() }
conditional_block
niche.rs
// run-pass //! Make sure that we read and write enum discriminants correctly for corner cases caused //! by layout optimizations. const OVERFLOW: usize = { // Tests for https://github.com/rust-lang/rust/issues/62138. #[repr(u8)] #[allow(dead_code)] enum WithWraparoundInvalidValues { X = 1, ...
<X> { V1 { f: bool }, /*_00*/ _01(X), _02(X), _03(X), _04(X), _05(X), _06(X), _07(X), _08(X), _09(X), _0A(X), _0B(X), _0C(X), _0D(X), _0E(X), _0F(X), _10(X), _11(X), _12(X), _13(X), _14(X), _15(X), _16(X), _17(X), _18(X), _19(X), _1A(X), _1B(X), _1C(X), _1D(X), _1E(X), _1F(X), ...
E2
identifier_name
59.rs
/* Problem 59: XOR decryption * * Each character on a computer is assigned a unique code and the preferred standard is ASCII * (American Standard Code for Information Interchange). For example, uppercase A = 65, asterisk (*) * = 42, and lowercase k = 107. * * A modern encryption method is to take a text file, con...
{ byte: u8, } const FIRST_LOWERCASE: u8 = b'a'; const LAST_LOWERCASE: u8 = b'z'; impl LowerCaseCharacter { fn from_byte(byte: u8) -> LowerCaseCharacter { if byte < FIRST_LOWERCASE || byte > LAST_LOWERCASE { panic!("Invalid byte: {}", byte); } else { LowerCaseCharacter ...
LowerCaseCharacter
identifier_name
59.rs
/* Problem 59: XOR decryption * * Each character on a computer is assigned a unique code and the preferred standard is ASCII * (American Standard Code for Information Interchange). For example, uppercase A = 65, asterisk (*) * = 42, and lowercase k = 107. * * A modern encryption method is to take a text file, con...
result.to_ascii_char().ok() }) } } #[derive(Copy, Clone)] struct LowerCaseCharacter { byte: u8, } const FIRST_LOWERCASE: u8 = b'a'; const LAST_LOWERCASE: u8 = b'z'; impl LowerCaseCharacter { fn from_byte(byte: u8) -> LowerCaseCharacter { if byte < FIRST_LOWERCASE || byte > LAS...
let result = value ^ self.key[pos % KEY_LEN].byte; self.position += 1;
random_line_split
traffic_signals.rs
// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in ...
if!current_cycle.turns.is_empty() { cycles.push(current_cycle.clone()); } // TODO second pass to add all legal turns to the cycles we came up with initially cycles } } #[derive(Clone, Debug)] pub struct Cycle { pub turns: Vec<TurnID>, // in the future, what ped...
} } // TODO not sure this condition is needed
random_line_split
traffic_signals.rs
// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in ...
pub fn current_cycle_and_remaining_time( &self, time: si::Second<f64>, ) -> (&Cycle, si::Second<f64>) { let cycle_idx = (time / CYCLE_DURATION).floor() as usize; let cycle = &self.cycles[cycle_idx % self.cycles.len()]; let next_cycle_time = (cycle_idx + 1) as f64 * CYCL...
{ self.cycles = state .cycles .iter() .map(|c| Cycle { turns: c.turns.clone(), changed: true, duration: CYCLE_DURATION, }) .collect(); }
identifier_body
traffic_signals.rs
// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in ...
Some(ModifiedTrafficSignal { cycles: self.cycles .iter() .map(|c| CycleState { turns: c.turns.clone(), }) .collect(), }) } pub fn load_savestate(&mut self, state: &ModifiedTrafficSignal) { self...
{ return None; }
conditional_block
traffic_signals.rs
// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in ...
(&self, t1: TurnID, geom_map: &GeomMap) -> bool { for t2 in &self.turns { if geom_map.get_t(t1).conflicts_with(geom_map.get_t(*t2)) { return true; } } false } pub fn contains(&self, t: TurnID) -> bool { self.turns.contains(&t) } p...
conflicts_with
identifier_name
weird-exprs.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 ...
(_x: ()) { } f(return); } fn what() { fn the(x: @mut bool) { return while!*x { *x = true; }; } let i = @mut false; let dont = {||the(i)}; dont(); assert!((*i)); } fn zombiejesus() { loop { while (return) { if (return) { match (return) { ...
f
identifier_name
weird-exprs.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 ...
break; } } fn evil_lincoln() { let _evil = info2!("lincoln"); } pub fn main() { strange(); funny(); what(); zombiejesus(); notsure(); canttouchthis(); angrydome(); evil_lincoln(); }
{ match (continue) { 1 => { }, _ => fail2!("wat") } }
conditional_block
weird-exprs.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 ...
strange(); funny(); what(); zombiejesus(); notsure(); canttouchthis(); angrydome(); evil_lincoln(); }
fn evil_lincoln() { let _evil = info2!("lincoln"); } pub fn main() {
random_line_split
weird-exprs.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 ...
let i = @mut false; let dont = {||the(i)}; dont(); assert!((*i)); } fn zombiejesus() { loop { while (return) { if (return) { match (return) { 1 => { if (return) { return ...
{ return while !*x { *x = true; }; }
identifier_body
cgram.rs
//! CGRAM definitions and methods use super::SnesRgb; /// Color RAM size in Bytes pub const CGRAM_SIZE: usize = 512; byte_array!(pub Cgram[CGRAM_SIZE] with u16 indexing, save state please); impl Cgram { /// Looks up a color in CGRAM and returns the RGB color values stored inside, without adjusting /// the c...
/// Set a raw color value /// /// `-bbbbbgg gggrrrrr` /// /// The raw color is converted to big endian and stored as 2 CGRAM bytes. pub fn set_color_raw(&mut self, index: u8, raw: u16) { self[index as u16 * 2] = raw as u8; self[index as u16 * 2 + 1] = (raw >> 8) as u8; } }
let hi = self[color as u16 * 2 + 1] as u16; (hi << 8) | lo }
random_line_split
cgram.rs
//! CGRAM definitions and methods use super::SnesRgb; /// Color RAM size in Bytes pub const CGRAM_SIZE: usize = 512; byte_array!(pub Cgram[CGRAM_SIZE] with u16 indexing, save state please); impl Cgram { /// Looks up a color in CGRAM and returns the RGB color values stored inside, without adjusting /// the c...
/// Set a raw color value /// /// `-bbbbbgg gggrrrrr` /// /// The raw color is converted to big endian and stored as 2 CGRAM bytes. pub fn set_color_raw(&mut self, index: u8, raw: u16) { self[index as u16 * 2] = raw as u8; self[index as u16 * 2 + 1] = (raw >> 8) as u8; } }
{ // -bbbbbgg gggrrrrr (16-bit big endian value! (high byte, high address first)) let lo = self[color as u16 * 2] as u16; let hi = self[color as u16 * 2 + 1] as u16; (hi << 8) | lo }
identifier_body
cgram.rs
//! CGRAM definitions and methods use super::SnesRgb; /// Color RAM size in Bytes pub const CGRAM_SIZE: usize = 512; byte_array!(pub Cgram[CGRAM_SIZE] with u16 indexing, save state please); impl Cgram { /// Looks up a color in CGRAM and returns the RGB color values stored inside, without adjusting /// the c...
(&self, color: u8) -> SnesRgb { // -bbbbbgg gggrrrrr (16-bit big endian value! (high byte, high address first)) let val = self.get_color_raw(color); // Extract components let b = (val & 0x7c00) >> 10; let g = (val & 0x03e0) >> 5; let r = val & 0x001f; SnesRgb::n...
get_color
identifier_name
02-discord_bot.rs
#[macro_use] extern crate serenity; extern crate gwent_api; extern crate serde; extern crate serde_json; use gwent_api::client::gw_client; use serenity::client::Client; use serenity::model::Mentionable; use std::env; fn
() { // Login with a bot token from the environment let mut client = Client::new(&env::var("DISCORD_TOKEN").expect("token")); client.with_framework(|f| f .configure(|c| c.prefix("!")) .on("card", card)); // start listening for events by starting a single shard let _ = client.start(); ...
main
identifier_name
02-discord_bot.rs
#[macro_use] extern crate serenity; extern crate gwent_api; extern crate serde; extern crate serde_json; use gwent_api::client::gw_client; use serenity::client::Client; use serenity::model::Mentionable; use std::env; fn main()
command!(card(_context, message) { let card_name = message.content.clone().split_off(6); println!("{}", card_name); match gw_client::Client::get_card_by_name(card_name.as_str()) { Err(_) => { let _ = message.reply("Card name is not recognized."); } Ok(card) => { ...
{ // Login with a bot token from the environment let mut client = Client::new(&env::var("DISCORD_TOKEN").expect("token")); client.with_framework(|f| f .configure(|c| c.prefix("!")) .on("card", card)); // start listening for events by starting a single shard let _ = client.start(); }
identifier_body
02-discord_bot.rs
#[macro_use] extern crate serenity;
extern crate gwent_api; extern crate serde; extern crate serde_json; use gwent_api::client::gw_client; use serenity::client::Client; use serenity::model::Mentionable; use std::env; fn main() { // Login with a bot token from the environment let mut client = Client::new(&env::var("DISCORD_TOKEN").expect("token...
random_line_split
syntax-ambiguity-2015.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 ...
while let Range { start: _, end: _ } = true..(true || false) { } while let Range { start: _, end: _ } = true..(true && false) { } }
{ }
conditional_block
syntax-ambiguity-2015.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 ...
() { use std::ops::Range; if let Range { start: _, end: _ } = true..true && false { } //~^ ERROR ambiguous use of `&&` if let Range { start: _, end: _ } = true..true || false { } //~^ ERROR ambiguous use of `||` while let Range { start: _, end: _ } = true..true && false { } //~^ ERROR amb...
main
identifier_name
syntax-ambiguity-2015.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 ...
while let Range { start: _, end: _ } = true..(true || false) { } while let Range { start: _, end: _ } = true..(true && false) { } }
random_line_split
syntax-ambiguity-2015.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 ...
// The following cases are not an error as parenthesis are used to // clarify intent: if let Range { start: _, end: _ } = true..(true || false) { } if let Range { start: _, end: _ } = true..(true && false) { } while let Range { start: _, end: _ } = true..(true || false) { } while let Range ...
{ use std::ops::Range; if let Range { start: _, end: _ } = true..true && false { } //~^ ERROR ambiguous use of `&&` if let Range { start: _, end: _ } = true..true || false { } //~^ ERROR ambiguous use of `||` while let Range { start: _, end: _ } = true..true && false { } //~^ ERROR ambigu...
identifier_body
file.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::FileBinding; use dom::bindings::codegen::Bindings::FileBinding::FileMethods;...
(global: GlobalRef, fileBits: Vec<BlobOrString>, filename: DOMString, filePropertyBag: &FileBinding::FilePropertyBag) -> Fallible<Root<File>> { let bytes: Vec<u8> = match blob_parts_to_bytes(fileBits) { Ok(by...
Constructor
identifier_name
file.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::FileBinding; use dom::bindings::codegen::Bindings::FileBinding::FileMethods;...
Err(_) => return Err(Error::InvalidCharacter), }; let ref blobPropertyBag = filePropertyBag.parent; let ref typeString = blobPropertyBag.type_; let modified = filePropertyBag.lastModified; // NOTE: Following behaviour might be removed in future, // see https...
-> Fallible<Root<File>> { let bytes: Vec<u8> = match blob_parts_to_bytes(fileBits) { Ok(bytes) => bytes,
random_line_split
file.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::FileBinding; use dom::bindings::codegen::Bindings::FileBinding::FileMethods;...
}
{ self.modified }
identifier_body
exposure.rs
* You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * S...
/* * Copyright (C) 2012 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License.
random_line_split
material.rs
use ray::Ray3; use hitable::HitRecord; use randomutil; use texture::Texture; use cgmath::{ Vector3, InnerSpace, Zero, }; use cgmath::num_traits::pow; pub fn scatter(material: &Material, r_in: &Ray3<f32>, hit_rec: &HitRecord) -> (Vector3<f32>, Ray3<f32>, bool) { match *material { Material::Meta...
(v: Vector3<f32>, n: Vector3<f32>, ni_over_nt: f32) -> (Vector3<f32>, bool) { let uv = v.normalize(); let dt = uv.dot(n); let discriminant = 1.0 - ni_over_nt * ni_over_nt * (1.0 - dt * dt); if discriminant > 0.0 { (ni_over_nt * (uv - n * dt) - n * discriminant.sqrt(), true) } else { ...
refract
identifier_name
material.rs
use ray::Ray3; use hitable::HitRecord; use randomutil; use texture::Texture; use cgmath::{ Vector3, InnerSpace, Zero, }; use cgmath::num_traits::pow; pub fn scatter(material: &Material, r_in: &Ray3<f32>, hit_rec: &HitRecord) -> (Vector3<f32>, Ray3<f32>, bool) { match *material { Material::Meta...
} Material::Lambertian { albedo } => { let target = hit_rec.p + hit_rec.normal + randomutil::random_in_unit_sphere(); (albedo, Ray3::new(hit_rec.p, target - hit_rec.p, r_in.time), true) } Material::TexturedLambertian { ref texture } => { let target = h...
let scattered = Ray3::new(hit_rec.p, reflected + fuzz * randomutil::random_in_unit_sphere(), r_in.time); let should_scatter = scattered.direction.dot(hit_rec.normal) > 0.0; (albedo, scattered, should_scatter)
random_line_split
material.rs
use ray::Ray3; use hitable::HitRecord; use randomutil; use texture::Texture; use cgmath::{ Vector3, InnerSpace, Zero, }; use cgmath::num_traits::pow; pub fn scatter(material: &Material, r_in: &Ray3<f32>, hit_rec: &HitRecord) -> (Vector3<f32>, Ray3<f32>, bool) { match *material { Material::Meta...
fn refract(v: Vector3<f32>, n: Vector3<f32>, ni_over_nt: f32) -> (Vector3<f32>, bool) { let uv = v.normalize(); let dt = uv.dot(n); let discriminant = 1.0 - ni_over_nt * ni_over_nt * (1.0 - dt * dt); if discriminant > 0.0 { (ni_over_nt * (uv - n * dt) - n * discriminant.sqrt(), true) } els...
{ v - 2.0 * v.dot(n) * n }
identifier_body
io.rs
use buf::{Buf, MutBuf}; use std::os::unix::io::{Fd, AsRawFd}; // Re-export the io::Result / Error types for convenience pub use std::io::{Read, Write, Result, Error}; /// A value that may be registered with an `EventLoop` pub trait Evented : AsRawFd { } /// Create a value with a FD pub trait FromFd { fn from_fd(...
impl TryRead for Io { fn read_slice(&mut self, dst: &mut [u8]) -> Result<Option<usize>> { use nix::unistd::read; read(self.as_raw_fd(), dst) .map(|cnt| Some(cnt)) .map_err(from_nix_error) .or_else(to_non_block) } } impl TryWrite for Io { fn write_slice(&mu...
} impl Evented for Io { }
random_line_split
io.rs
use buf::{Buf, MutBuf}; use std::os::unix::io::{Fd, AsRawFd}; // Re-export the io::Result / Error types for convenience pub use std::io::{Read, Write, Result, Error}; /// A value that may be registered with an `EventLoop` pub trait Evented : AsRawFd { } /// Create a value with a FD pub trait FromFd { fn from_fd(...
<B: MutBuf>(&mut self, buf: &mut B) -> Result<Option<usize>> { // Reads the length of the slice supplied by buf.mut_bytes into the buffer // This is not guaranteed to consume an entire datagram or segment. // If your protocol is msg based (instead of continuous stream) you should // ensu...
read
identifier_name
io.rs
use buf::{Buf, MutBuf}; use std::os::unix::io::{Fd, AsRawFd}; // Re-export the io::Result / Error types for convenience pub use std::io::{Read, Write, Result, Error}; /// A value that may be registered with an `EventLoop` pub trait Evented : AsRawFd { } /// Create a value with a FD pub trait FromFd { fn from_fd(...
Err(err) }
{ return Ok(None); }
conditional_block
io.rs
use buf::{Buf, MutBuf}; use std::os::unix::io::{Fd, AsRawFd}; // Re-export the io::Result / Error types for convenience pub use std::io::{Read, Write, Result, Error}; /// A value that may be registered with an `EventLoop` pub trait Evented : AsRawFd { } /// Create a value with a FD pub trait FromFd { fn from_fd(...
} /* * * ===== Pipe ===== * */ pub fn pipe() -> Result<(PipeReader, PipeWriter)> { use nix::fcntl::{O_NONBLOCK, O_CLOEXEC}; use nix::unistd::pipe2; let (rd, wr) = try!(pipe2(O_NONBLOCK | O_CLOEXEC) .map_err(from_nix_error)); let rd = FromFd::from_fd(rd); let wr = FromFd::from_fd(wr);...
{ use nix::unistd::close; let _ = close(self.as_raw_fd()); }
identifier_body
flatmap.rs
#![crate_name = "sknife"] /// Flatten and map on a list /// /// # Arguments /// /// * `f` - the map function /// * `list` - A slice of elements to flatten and map /// /// # Example /// /// ``` /// use sknife::collection::flatmap; /// let mut list: Vec<i32> = (1..4).collect(); /// let slice: &mut [i32] = list.as_mut_sl...
<A, F>(list: &mut [A], mut f: F) -> Vec<A> where F: FnMut(&mut A) -> Vec<A> { let mut vec = Vec::new(); for l in list { vec.extend(f(l)) } vec } mod tests { use super::*; #[test] fn flatmap_empty_list() { let mut list: Vec<i32> = vec![]; let slice: &mut [i32] = list.as_mut_slic...
flatmap
identifier_name
flatmap.rs
#![crate_name = "sknife"] /// Flatten and map on a list /// /// # Arguments /// /// * `f` - the map function /// * `list` - A slice of elements to flatten and map /// /// # Example /// /// ``` /// use sknife::collection::flatmap; /// let mut list: Vec<i32> = (1..4).collect(); /// let slice: &mut [i32] = list.as_mut_sl...
mod tests { use super::*; #[test] fn flatmap_empty_list() { let mut list: Vec<i32> = vec![]; let slice: &mut [i32] = list.as_mut_slice(); assert_eq!( flatmap(slice, |x: &mut i32| vec![*x]), vec![] ); } #[test] fn flatmap_list() { ...
{ let mut vec = Vec::new(); for l in list { vec.extend(f(l)) } vec }
identifier_body
flatmap.rs
#![crate_name = "sknife"] /// Flatten and map on a list /// /// # Arguments /// /// * `f` - the map function /// * `list` - A slice of elements to flatten and map /// /// # Example /// /// ``` /// use sknife::collection::flatmap; /// let mut list: Vec<i32> = (1..4).collect(); /// let slice: &mut [i32] = list.as_mut_sl...
where F: FnMut(&mut A) -> Vec<A> { let mut vec = Vec::new(); for l in list { vec.extend(f(l)) } vec } mod tests { use super::*; #[test] fn flatmap_empty_list() { let mut list: Vec<i32> = vec![]; let slice: &mut [i32] = list.as_mut_slice(); assert_eq!( flatmap...
/// # Result /// ``` /// vec![1, 2, 3]; /// ``` pub fn flatmap<A, F>(list: &mut [A], mut f: F) -> Vec<A>
random_line_split
windowing.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/. */ //! Abstract windowing methods. The concrete implementations of these can be found in `platform/`. use compositor...
(&self, f: &mut Formatter) -> Result<(),Error> { match *self { WindowEvent::Idle => write!(f, "Idle"), WindowEvent::Refresh => write!(f, "Refresh"), WindowEvent::InitializeCompositing => write!(f, "InitializeCompositing"), WindowEvent::Resize(..) => write!(f, "Res...
fmt
identifier_name
windowing.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/. */ //! Abstract windowing methods. The concrete implementations of these can be found in `platform/`. use compositor...
/// Process a key event. fn handle_key(&self, key: Key, mods: KeyModifiers); }
random_line_split
shootout-fasta-redux.rs
// The Computer Language Benchmarks Game // http://benchmarksgame.alioth.debian.org/ // // contributed by the Rust Project Developers // Copyright (c) 2013-2014 The Rust Project Developers // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted...
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE ...
// written permission. //
random_line_split
shootout-fasta-redux.rs
// The Computer Language Benchmarks Game // http://benchmarksgame.alioth.debian.org/ // // contributed by the Rust Project Developers // Copyright (c) 2013-2014 The Rust Project Developers // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted...
} 0 } fn make(&mut self, n: uint) -> IoResult<()> { let lines = n / LINE_LEN; let chars_left = n % LINE_LEN; let mut buf = [0,..LINE_LEN + 1]; for _ in range(0, lines) { for i in range(0u, LINE_LEN) { buf[i] = self.nextc(); ...
{ return a.c; }
conditional_block
shootout-fasta-redux.rs
// The Computer Language Benchmarks Game // http://benchmarksgame.alioth.debian.org/ // // contributed by the Rust Project Developers // Copyright (c) 2013-2014 The Rust Project Developers // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted...
fn nextc(&mut self) -> u8 { let r = self.rng(1.0); for a in self.lookup.iter() { if a.p >= r { return a.c; } } 0 } fn make(&mut self, n: uint) -> IoResult<()> { let lines = n / LINE_LEN; let chars_left = n % LINE_LEN;...
{ self.seed = (self.seed * IA + IC) % IM; max * (self.seed as f32) / (IM as f32) }
identifier_body
shootout-fasta-redux.rs
// The Computer Language Benchmarks Game // http://benchmarksgame.alioth.debian.org/ // // contributed by the Rust Project Developers // Copyright (c) 2013-2014 The Rust Project Developers // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted...
() { let args = os::args(); let args = args.as_slice(); let n = if args.len() > 1 { from_str::<uint>(args[1].as_slice()).unwrap() } else { 5 }; let mut out = stdout(); out.write_line(">ONE Homo sapiens alu").unwrap(); { let mut repeat = RepeatFasta::new(ALU, &mu...
main
identifier_name
option_map_or_none.rs
use clippy_utils::diagnostics::span_lint_and_sugg; use clippy_utils::is_lang_ctor; use clippy_utils::source::snippet; use clippy_utils::ty::is_type_diagnostic_item; use rustc_errors::Applicability; use rustc_hir as hir; use rustc_hir::LangItem::{OptionNone, OptionSome}; use rustc_lint::LateContext; use rustc_span::symb...
; if!default_arg_is_none { // nothing to lint! return; } let f_arg_is_some = if let hir::ExprKind::Path(ref qpath) = map_arg.kind { is_lang_ctor(cx, qpath, OptionSome) } else { false }; if is_option { let self...
{ return; }
conditional_block
option_map_or_none.rs
use clippy_utils::diagnostics::span_lint_and_sugg; use clippy_utils::is_lang_ctor; use clippy_utils::source::snippet; use clippy_utils::ty::is_type_diagnostic_item; use rustc_errors::Applicability; use rustc_hir as hir; use rustc_hir::LangItem::{OptionNone, OptionSome}; use rustc_lint::LateContext; use rustc_span::symb...
<'tcx>( cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>, recv: &'tcx hir::Expr<'_>, def_arg: &'tcx hir::Expr<'_>, map_arg: &'tcx hir::Expr<'_>, ) { let is_option = is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(recv), sym::option_type); let is_result = is_type_diagnostic_item(cx, ...
check
identifier_name
option_map_or_none.rs
use clippy_utils::diagnostics::span_lint_and_sugg; use clippy_utils::is_lang_ctor; use clippy_utils::source::snippet; use clippy_utils::ty::is_type_diagnostic_item; use rustc_errors::Applicability; use rustc_hir as hir; use rustc_hir::LangItem::{OptionNone, OptionSome}; use rustc_lint::LateContext; use rustc_span::symb...
if!default_arg_is_none { // nothing to lint! return; } let f_arg_is_some = if let hir::ExprKind::Path(ref qpath) = map_arg.kind { is_lang_ctor(cx, qpath, OptionSome) } else { false }; if is_option { let self_sn...
{ let is_option = is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(recv), sym::option_type); let is_result = is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(recv), sym::result_type); // There are two variants of this `map_or` lint: // (1) using `map_or` as an adapter from `Result<T,E>` t...
identifier_body
option_map_or_none.rs
use clippy_utils::diagnostics::span_lint_and_sugg; use clippy_utils::is_lang_ctor; use clippy_utils::source::snippet; use clippy_utils::ty::is_type_diagnostic_item; use rustc_errors::Applicability; use rustc_hir as hir; use rustc_hir::LangItem::{OptionNone, OptionSome}; use rustc_lint::LateContext; use rustc_span::symb...
def_arg: &'tcx hir::Expr<'_>, map_arg: &'tcx hir::Expr<'_>, ) { let is_option = is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(recv), sym::option_type); let is_result = is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(recv), sym::result_type); // There are two variants of this `map_...
recv: &'tcx hir::Expr<'_>,
random_line_split
lib.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
time(time_passes, "type checking", (), |_| check::check_item_types(&ccx)); check_for_entry_fn(&ccx); tcx.sess.abort_if_errors(); } #[cfg(stage0)] __build_diagnostic_array! { DIAGNOSTICS } #[cfg(not(stage0))] __build_diagnostic_array! { librustc_typeck, DIAGNOSTICS }
{ let time_passes = tcx.sess.time_passes(); let ccx = CrateCtxt { trait_map: trait_map, all_traits: RefCell::new(None), tcx: tcx }; time(time_passes, "type collecting", (), |_| collect::collect_item_types(tcx)); // this ensures that later parts of type checking can...
identifier_body
lib.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
<'tcx> { pub substs: subst::Substs<'tcx>, pub ty: Ty<'tcx>, } pub struct CrateCtxt<'a, 'tcx: 'a> { // A mapping from method call sites to traits that have that method. trait_map: ty::TraitMap, /// A vector of every trait accessible in the whole crate /// (i.e. including those from subcrates). T...
TypeAndSubsts
identifier_name
lib.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
_ => { tcx.sess.span_bug(main_span, &format!("main has a non-function type: found \ `{}`", ppaux::ty_to_string(tcx, main_t))); } ...
}); }
random_line_split
reader.rs
use rustc_serialize::json::{Json, Object}; use std::fs::File; use super::responses::Responses; use super::outcome::Outcome; pub struct Phase { pub operation: Responses, pub outcome: Outcome, } impl Phase { fn from_json(object: &Object) -> Result<Phase, String> { let operation = val_or_err!(object...
pub struct Suite { pub uri: String, pub phases: Vec<Phase>, } fn get_phases(object: &Object) -> Result<Vec<Phase>, String> { let array = val_or_err!(object.get("phases"), Some(&Json::Array(ref array)) => array.clone(), "No `phases` array found"); ...
"No `outcome` object found."); Ok(Phase{ operation: operation, outcome: outcome }) } }
random_line_split
reader.rs
use rustc_serialize::json::{Json, Object}; use std::fs::File; use super::responses::Responses; use super::outcome::Outcome; pub struct Phase { pub operation: Responses, pub outcome: Outcome, } impl Phase { fn from_json(object: &Object) -> Result<Phase, String> { let operation = val_or_err!(object...
(path: &str) -> Result<Json, String> { let mut file = File::open(path).ok().expect(&format!("Unable to open file: {}", path)); Ok(Json::from_reader(&mut file).ok().expect(&format!("Invalid JSON file: {}", path))) } fn get_suite(&self) -> Result<Suite, String> { let object = val_or_err!...
from_file
identifier_name
reader.rs
use rustc_serialize::json::{Json, Object}; use std::fs::File; use super::responses::Responses; use super::outcome::Outcome; pub struct Phase { pub operation: Responses, pub outcome: Outcome, } impl Phase { fn from_json(object: &Object) -> Result<Phase, String>
} pub struct Suite { pub uri: String, pub phases: Vec<Phase>, } fn get_phases(object: &Object) -> Result<Vec<Phase>, String> { let array = val_or_err!(object.get("phases"), Some(&Json::Array(ref array)) => array.clone(), "No `phases` array found"); ...
{ let operation = val_or_err!(object.get("responses"), Some(&Json::Array(ref array)) => try!(Responses::from_json(array)), "No `responses` array found."); let outcome = val_or_err!(object.get("outcome"), ...
identifier_body
session.rs
#![allow(non_snake_case)] use serde_json; use std::thread; use std::time::Duration; use request::Handler; use error::ConsulResult; use std::error::Error; pub const SESSION_TTL: &'static str = "15s"; #[derive(Serialize, Deserialize, Debug)] pub struct SessionCreate { Name: String, TTL: String } #[derive(Ser...
(&self, session_id: &String) -> ConsulResult<bool> { for _ in 0..10 { let uri = format!("renew/{}", session_id); match self.handler.put(&uri, "".to_owned(), Some("application/json")) { Ok(_) => return Ok(true), Err(e) => { println!("Cou...
renew
identifier_name
session.rs
#![allow(non_snake_case)] use serde_json; use std::thread; use std::time::Duration; use request::Handler; use error::ConsulResult; use std::error::Error; pub const SESSION_TTL: &'static str = "15s"; #[derive(Serialize, Deserialize, Debug)] pub struct SessionCreate { Name: String, TTL: String } #[derive(Ser...
pub fn end(&self, session_id: &String) -> ConsulResult<()> { let uri = format!("destroy/{}", session_id); self.handler.put(&uri, "".to_owned(), Some("application/json"))?; Ok(()) } }
}
random_line_split
nodelist.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::NodeListBinding; use dom::bindings::js::JS; use dom::bindings::utils::{Reflectable, Re...
pub fn IndexedGetter(&self, index: u32, found: &mut bool) -> Option<JS<Node>> { let item = self.Item(index); *found = item.is_some(); item } } impl Reflectable for NodeList { fn reflector<'a>(&'a self) -> &'a Reflector { &self.reflector_ } fn mut_reflector<'a>(&'a...
{ match self.list_type { _ if index >= self.Length() => None, Simple(ref elems) => Some(elems[index].clone()), Children(ref node) => node.children().nth(index as uint) } }
identifier_body
nodelist.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::NodeListBinding;
use dom::window::Window; #[deriving(Encodable)] pub enum NodeListType { Simple(~[JS<Node>]), Children(JS<Node>) } #[deriving(Encodable)] pub struct NodeList { list_type: NodeListType, reflector_: Reflector, window: JS<Window> } impl NodeList { pub fn new_inherited(window: JS<Window>, ...
use dom::bindings::js::JS; use dom::bindings::utils::{Reflectable, Reflector, reflect_dom_object}; use dom::node::{Node, NodeHelpers};
random_line_split
nodelist.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::NodeListBinding; use dom::bindings::js::JS; use dom::bindings::utils::{Reflectable, Re...
<'a>(&'a mut self) -> &'a mut Reflector { &mut self.reflector_ } }
mut_reflector
identifier_name
p_1_1_1_01.rs
// P_1_1_1_01 // // Generative Gestaltung – Creative Coding im Web // ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018 // Benedikt Groß, Hartmut Bohnacker, Julia Laub, Claudius Lazzeroni // with contributions by Joey Lee and Niels Poldervaart // Copyright 2018 // // http://www.generative-gestaltung....
{ nannou::sketch(view).size(800, 400).run(); } fn view(app: &App, frame: Frame) { // Begin drawing let draw = app.draw(); draw.background().color(BLACK); let win_rect = app.window_rect(); let step_x = (app.mouse.x - win_rect.left()).max(5.0); let step_y = (win_rect.top() - app.mouse.y).ma...
n()
identifier_name
p_1_1_1_01.rs
// P_1_1_1_01 // // Generative Gestaltung – Creative Coding im Web // ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018 // Benedikt Groß, Hartmut Bohnacker, Julia Laub, Claudius Lazzeroni // with contributions by Joey Lee and Niels Poldervaart // Copyright 2018 // // http://www.generative-gestaltung....
draw.to_frame(app, &frame).unwrap(); }
random_line_split
p_1_1_1_01.rs
// P_1_1_1_01 // // Generative Gestaltung – Creative Coding im Web // ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018 // Benedikt Groß, Hartmut Bohnacker, Julia Laub, Claudius Lazzeroni // with contributions by Joey Lee and Niels Poldervaart // Copyright 2018 // // http://www.generative-gestaltung....
n view(app: &App, frame: Frame) { // Begin drawing let draw = app.draw(); draw.background().color(BLACK); let win_rect = app.window_rect(); let step_x = (app.mouse.x - win_rect.left()).max(5.0); let step_y = (win_rect.top() - app.mouse.y).max(5.0); let size = vec2(step_x, step_y); let...
nannou::sketch(view).size(800, 400).run(); } f
identifier_body
deriving-via-extension-enum.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 http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #[deriving(Parti...
random_line_split
deriving-via-extension-enum.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 ...
() { let a = Foo::Bar(1, 2); let b = Foo::Bar(1, 2); assert_eq!(a, b); assert!(!(a!= b)); assert!(a.eq(&b)); assert!(!a.ne(&b)); }
main
identifier_name
refptr.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/. */ //! A rust helper to ease the use of Gecko's refcounted types. use crate::gecko_bindings::sugar::ownership::HasA...
<T: RefCounted>(RefPtr<T>); // There is no safe conversion from &T to RefPtr<T> (like Gecko has) // because this lets you break UniqueRefPtr's guarantee impl<T: RefCounted> RefPtr<T> { /// Create a new RefPtr from an already addrefed pointer obtained from FFI. /// /// The pointer must be valid, non-null a...
UniqueRefPtr
identifier_name
refptr.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/. */ //! A rust helper to ease the use of Gecko's refcounted types. use crate::gecko_bindings::sugar::ownership::HasA...
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str("RefPtr { ")?; self.ptr.fmt(f)?; f.write_str("}") } } /// A RefPtr that we know is uniquely owned. /// /// This is basically Box<T>, with the additional guarantee that the box can be /// safely interpreted as a RefPtr<T>...
_marker: PhantomData<T>, } impl<T: RefCounted> fmt::Debug for RefPtr<T> {
random_line_split
refptr.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/. */ //! A rust helper to ease the use of Gecko's refcounted types. use crate::gecko_bindings::sugar::ownership::HasA...
/// Replace a structs::RefPtr<T> with a different one, appropriately /// addref/releasing. /// /// Both `self` and `other` must be valid, but can be null. /// /// Safe when called on an aliased pointer because the refcount in that case /// needs to be at least two. pub unsafe fn set(&m...
{ debug_assert!(!self.mRawPtr.is_null()); RefPtr { ptr: self.mRawPtr, _marker: PhantomData, } }
identifier_body
refptr.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/. */ //! A rust helper to ease the use of Gecko's refcounted types. use crate::gecko_bindings::sugar::ownership::HasA...
*self = other.forget(); } } impl<T> structs::RefPtr<T> { /// Sets the contents to an `Arc<T>`, releasing the old value in `self` if /// necessary. pub fn set_arc<U>(&mut self, other: Arc<U>) where U: HasArcFFI<FFIType = T>, { unsafe { U::release_opt(self.mRa...
{ unsafe { (*self.mRawPtr).release(); } }
conditional_block
unwind-match.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 ...
let res = match false { true => { "happy".to_string() }, _ => fail!("non-exhaustive match failure") }; assert_eq!(res, "happy".to_string()); } fn main() { test_box(); test_str(); }
fn test_box() { box(GC) 0i; } fn test_str() {
random_line_split
unwind-match.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 ...
{ test_box(); test_str(); }
identifier_body
unwind-match.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 ...
, _ => fail!("non-exhaustive match failure") }; assert_eq!(res, "happy".to_string()); } fn main() { test_box(); test_str(); }
{ "happy".to_string() }
conditional_block
unwind-match.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 ...
() { box(GC) 0i; } fn test_str() { let res = match false { true => { "happy".to_string() }, _ => fail!("non-exhaustive match failure") }; assert_eq!(res, "happy".to_string()); } fn main() { test_box(); test_str(); }
test_box
identifier_name
type-params-in-for-each.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 ...
(lo: uint, hi: uint, it: &fn(uint)) { let mut lo_ = lo; while lo_ < hi { it(lo_); lo_ += 1u; } } fn create_index<T>(_index: ~[S<T>], _hash_fn: extern fn(T) -> uint) { do range_(0u, 256u) |_i| { let _bucket: ~[T] = ~[]; } } pub fn main() { }
range_
identifier_name
type-params-in-for-each.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 ...
} } pub fn main() { }
fn create_index<T>(_index: ~[S<T>], _hash_fn: extern fn(T) -> uint) { do range_(0u, 256u) |_i| { let _bucket: ~[T] = ~[];
random_line_split
type-params-in-for-each.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 ...
{ }
identifier_body
tetris.rs
extern crate input; extern crate graphics; // External Imports use std::default::Default; use opengl_graphics::{Gl, Texture}; use event::{Window, UpdateArgs, RenderArgs,}; use self::graphics::*; use self::input::{keyboard, Button, Keyboard,}; // Project Imports use active::ActiveTetromino; use tetromino::Color; use s...
pub fn render<W: Window>(&mut self, _: &mut W, gl: &mut Gl, args: &RenderArgs) { // Set up a context to draw into. let context = &Context::abs(args.width as f64, args.height as f64); context.rgba(0.0,0.0,0.0,1.0).draw(gl); let c = context.zoom(self.scale); fn pos(n: uint) -> f64 { n as f64 * TI...
{ assets.push("block.png"); self.block = Some(Texture::from_path(assets).unwrap()); }
identifier_body