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
extract.rs
use std::fs; use std::io; fn main() { std::process::exit(real_main()); } fn
() -> i32 { let args: Vec<_> = std::env::args().collect(); if args.len() < 2 { println!("Usage: {} ", args[0]); return 1; } let fname = std::path::Path::new(&*args[1]); let file = fs::File::open(&fname).unwrap(); let mut archive = zip::ZipArchive::new(file).unwrap(); for i ...
real_main
identifier_name
global_int.rs
// RUN: %build_test_apk --driver driver-int-param --out %t --testcase %s %build_test_apk_opts // RUN: %Test_jit_debuginfo %s %t // DEBUGGER: source android-commands.py // DEBUGGER: load-android-app %t // DEBUGGER: set breakpoint pending on // DEBUGGER: b %s:46 // DEBUGGER: run-android-app // DEBUGGER: p global_zero //...
else { global_zero += 1; } global_zero += global_value; }
{ global_value += 10; }
conditional_block
global_int.rs
// RUN: %build_test_apk --driver driver-int-param --out %t --testcase %s %build_test_apk_opts // RUN: %Test_jit_debuginfo %s %t
// DEBUGGER: b %s:46 // DEBUGGER: run-android-app // DEBUGGER: p global_zero // DEBUGGER: p global_value // CHECK: $1 = 0 // CHECK: $2 = 11 #pragma version(1) #pragma rs java_package_name(%PACKAGE%) // a global value int global_zero = 0; int global_value = 1; static int twenty() { return 20; } static int some_fun...
// DEBUGGER: source android-commands.py // DEBUGGER: load-android-app %t // DEBUGGER: set breakpoint pending on
random_line_split
simd-array-trait.rs
// Figuring out the size of a vector type that depends on traits doesn't ICE #![allow(dead_code)] // pretty-expanded FIXME #23616 #![feature(repr_simd, platform_intrinsics, generic_const_exprs)] #![allow(non_camel_case_types, incomplete_features)] pub trait Simd { type Lane: Clone + Copy; const SIZE: usize;...
{ let mut t = T::<i32x4>([0; 4]); unsafe { for i in 0_i32..4 { t = simd_insert(t, i as u32, i); } for i in 0_i32..4 { assert_eq!(i, simd_extract(t, i as u32)); } } }
identifier_body
simd-array-trait.rs
// Figuring out the size of a vector type that depends on traits doesn't ICE #![allow(dead_code)] // pretty-expanded FIXME #23616 #![feature(repr_simd, platform_intrinsics, generic_const_exprs)] #![allow(non_camel_case_types, incomplete_features)] pub trait Simd { type Lane: Clone + Copy; const SIZE: usize;...
; impl Simd for i32x4 { type Lane = i32; const SIZE: usize = 4; } #[repr(simd)] #[derive(Copy, Clone)] pub struct T<S: Simd>([S::Lane; S::SIZE]); //~^ ERROR unconstrained generic constant extern "platform-intrinsic" { fn simd_insert<T, E>(x: T, idx: u32, y: E) -> T; fn simd_extract<T, E>(x: T, idx: u3...
i32x4
identifier_name
simd-array-trait.rs
// Figuring out the size of a vector type that depends on traits doesn't ICE #![allow(dead_code)] // pretty-expanded FIXME #23616
#![feature(repr_simd, platform_intrinsics, generic_const_exprs)] #![allow(non_camel_case_types, incomplete_features)] pub trait Simd { type Lane: Clone + Copy; const SIZE: usize; } pub struct i32x4; impl Simd for i32x4 { type Lane = i32; const SIZE: usize = 4; } #[repr(simd)] #[derive(Copy, Clone)] p...
random_line_split
rt.rs
#![deny(unsafe_op_in_unsafe_fn)] #![allow(unused_macros)] use crate::sync::Once; use crate::sys; use crate::sys_common::thread_info; use crate::thread::Thread; // One-time runtime initialization. // Runs before `main`. // SAFETY: must be called only once during runtime initialization. // NOTE: this is not guaranteed ...
(argc: isize, argv: *const *const u8) { unsafe { sys::init(argc, argv); let main_guard = sys::thread::guard::init(); // Next, set up the current Thread with the guard information we just // created. Note that this isn't necessary in general for new threads, // but we just do...
init
identifier_name
rt.rs
#![deny(unsafe_op_in_unsafe_fn)] #![allow(unused_macros)] use crate::sync::Once; use crate::sys; use crate::sys_common::thread_info; use crate::thread::Thread; // One-time runtime initialization. // Runs before `main`. // SAFETY: must be called only once during runtime initialization. // NOTE: this is not guaranteed ...
let err = err.as_ref().map(drop); // map Ok/Some which might not be Debug rtabort!(concat!("unwrap failed: ", stringify!($e), " = {:?}"), err) } } }; }
$ok(v) => v, ref err => {
random_line_split
rt.rs
#![deny(unsafe_op_in_unsafe_fn)] #![allow(unused_macros)] use crate::sync::Once; use crate::sys; use crate::sys_common::thread_info; use crate::thread::Thread; // One-time runtime initialization. // Runs before `main`. // SAFETY: must be called only once during runtime initialization. // NOTE: this is not guaranteed ...
// One-time runtime cleanup. // Runs after `main` or at program exit. // NOTE: this is not guaranteed to run, for example when the program aborts. #[cfg_attr(test, allow(dead_code))] pub fn cleanup() { static CLEANUP: Once = Once::new(); CLEANUP.call_once(|| unsafe { // Flush stdout and disable buffer...
{ unsafe { sys::init(argc, argv); let main_guard = sys::thread::guard::init(); // Next, set up the current Thread with the guard information we just // created. Note that this isn't necessary in general for new threads, // but we just do this to name the main thread and to g...
identifier_body
buffer.rs
use std::cmp; use std::iter; use std::io::{self, Read, BufRead}; pub struct BufReader<R> { inner: R, buf: Vec<u8>, pos: usize, cap: usize, } const INIT_BUFFER_SIZE: usize = 4096; const MAX_BUFFER_SIZE: usize = 8192 + 4096 * 100; impl<R: Read> BufReader<R> { #[inline] pub fn new(rdr: R) -> Buf...
} } impl<R: Read> Read for BufReader<R> { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { if self.cap == self.pos && buf.len() >= self.buf.len() { return self.inner.read(buf); } let nread = { let mut rem = try!(self.fill_buf()); try!(rem.read(...
random_line_split
buffer.rs
use std::cmp; use std::iter; use std::io::{self, Read, BufRead}; pub struct BufReader<R> { inner: R, buf: Vec<u8>, pos: usize, cap: usize, } const INIT_BUFFER_SIZE: usize = 4096; const MAX_BUFFER_SIZE: usize = 8192 + 4096 * 100; impl<R: Read> BufReader<R> { #[inline] pub fn new(rdr: R) -> Buf...
#[inline] pub fn read_into_buf(&mut self) -> io::Result<usize> { self.maybe_reserve(); let v = &mut self.buf; trace!("read_into_buf pos={}, cap={}", self.cap, v.capacity()); if self.cap < v.capacity() { let nread = try!(self.inner.read(&mut v[self.cap..])); ...
{ self.inner }
identifier_body
buffer.rs
use std::cmp; use std::iter; use std::io::{self, Read, BufRead}; pub struct BufReader<R> { inner: R, buf: Vec<u8>, pos: usize, cap: usize, } const INIT_BUFFER_SIZE: usize = 4096; const MAX_BUFFER_SIZE: usize = 8192 + 4096 * 100; impl<R: Read> BufReader<R> { #[inline] pub fn new(rdr: R) -> Buf...
(&mut self, amt: usize) { self.pos = cmp::min(self.pos + amt, self.cap); if self.pos == self.cap { self.pos = 0; self.cap = 0; } } } #[cfg(test)] mod tests { use std::io::{self, Read, BufRead}; use super::BufReader; struct SlowRead(u8); impl Read f...
consume
identifier_name
integration.rs
extern crate stratis_shared as shared; extern crate stratis; extern crate rand; use stratis::{Server,Client}; use shared::opcode; use shared::events::Event; use std::thread; use std::time::Duration; use std::sync::{Arc, Mutex}; use std::sync::mpsc::Receiver; use rand::distributions::{IndependentSample,Range}; fn a...
(client,rx) } #[test] fn client () { let (_client, rx) = assert_client(); thread::sleep(Duration::from_millis(100)); // we recv player twice // once for our own login // and again for each player that's connected assert_opcode(&rx,opcode::PLAYER); assert_opcode(&rx,opcode::PLAYER...
assert!(client.lock().unwrap().stream.is_some());
random_line_split
integration.rs
extern crate stratis_shared as shared; extern crate stratis; extern crate rand; use stratis::{Server,Client}; use shared::opcode; use shared::events::Event; use std::thread; use std::time::Duration; use std::sync::{Arc, Mutex}; use std::sync::mpsc::Receiver; use rand::distributions::{IndependentSample,Range}; fn a...
#[test] fn client_chat () { let (client, rx) = assert_client(); thread::sleep(Duration::from_millis(100)); let text = "test"; client.lock().unwrap().chat(text); assert_opcode(&rx,opcode::PLAYER); assert_opcode(&rx,opcode::PLAYER); thread::sleep(Duration::from_millis(10)); le...
{ let (_client, rx) = assert_client(); thread::sleep(Duration::from_millis(100)); // we recv player twice // once for our own login // and again for each player that's connected assert_opcode(&rx,opcode::PLAYER); assert_opcode(&rx,opcode::PLAYER); }
identifier_body
integration.rs
extern crate stratis_shared as shared; extern crate stratis; extern crate rand; use stratis::{Server,Client}; use shared::opcode; use shared::events::Event; use std::thread; use std::time::Duration; use std::sync::{Arc, Mutex}; use std::sync::mpsc::Receiver; use rand::distributions::{IndependentSample,Range}; fn a...
() { let (_client, rx) = assert_client(); thread::sleep(Duration::from_millis(100)); // we recv player twice // once for our own login // and again for each player that's connected assert_opcode(&rx,opcode::PLAYER); assert_opcode(&rx,opcode::PLAYER); } #[test] fn client_chat () { ...
client
identifier_name
simple-user-login.rs
extern crate passwors; use passwors::*; use std::collections::HashMap; // This is just a simplified version of what // your database entries might look like. // You don't need much more than that. pub struct User { pub name: String, pub password: HashedPassword, pub salt: HashSalt, pub hash...
} fn main() { let mut db = UserDB::new(); // Let's first add a new user with really // shitty login credentials. { let hasher = Argon2Settings::new().try_create().unwrap(); let salt = HashSalt::new().unwrap(); let pw_hash = { // Every time you use such passwords, a...
{ self.all_users.get(name) }
identifier_body
simple-user-login.rs
extern crate passwors; use passwors::*; use std::collections::HashMap; // This is just a simplified version of what // your database entries might look like. // You don't need much more than that. pub struct User { pub name: String, pub password: HashedPassword, pub salt: HashSalt, pub hashe...
assert_eq!(user.password, pw_hash); // Now, if your application detects that the user's // hasher settings are different from your current // default, you would actually hash the password twice, // the second time using the new settings. You would // then simply replace the old password hash wi...
};
random_line_split
simple-user-login.rs
extern crate passwors; use passwors::*; use std::collections::HashMap; // This is just a simplified version of what // your database entries might look like. // You don't need much more than that. pub struct User { pub name: String, pub password: HashedPassword, pub salt: HashSalt, pub hash...
(&mut self, user: User) { let name = user.name.clone(); self.all_users.insert(name, user); } // Now, to upgrade hasher settings in case we // changed them, we'd obviously need a mutable // reference. However, this is way beyond this // example. pub fn find_user(&self, name: &str...
add_user
identifier_name
bodyparser.rs
extern crate iron; extern crate bodyparser; extern crate persistent; extern crate serde; use persistent::Read; use iron::status; use iron::prelude::*; use serde::{Deserialize, Deserializer}; use serde::de::{MapVisitor, Visitor}; #[derive(Debug, Clone)] struct MyStructure { a: String, b: Option<String>, } // ...
} } // Same as above. In your own code you won't need to implement this manually. enum MyStructureField { A, B, } // Same as above. In your own code you won't need to implement this manually. impl Deserialize for MyStructureField { fn deserialize<D>(deserializer: &mut D) -> Result<MyStructureField, D:...
random_line_split
bodyparser.rs
extern crate iron; extern crate bodyparser; extern crate persistent; extern crate serde; use persistent::Read; use iron::status; use iron::prelude::*; use serde::{Deserialize, Deserializer}; use serde::de::{MapVisitor, Visitor}; #[derive(Debug, Clone)] struct MyStructure { a: String, b: Option<String>, } // ...
{ A, B, } // Same as above. In your own code you won't need to implement this manually. impl Deserialize for MyStructureField { fn deserialize<D>(deserializer: &mut D) -> Result<MyStructureField, D::Error> where D: Deserializer { struct MyStructureFieldVisitor; impl Visitor fo...
MyStructureField
identifier_name
cas.rs
extern crate url; extern crate hyper; extern crate xml; use self::url::{Url, ParseError}; use self::hyper::server::response::Response; use self::hyper::server::request::Request; use self::hyper::status::StatusCode; use self::hyper::header::Location; use self::hyper::Client; use self::hyper::error::Error as HyperError;...
(&self, ticket: &str) -> Result<ServiceResponse, VerifyError> { let mut url: Url = self.verify_url.clone(); let param = vec![ ("service", self.service_url.serialize()), ("ticket", ticket.to_string()), ]; url.set_query_from_pairs(param); let res = try!(Cli...
verify_ticket
identifier_name
cas.rs
extern crate url; extern crate hyper; extern crate xml; use self::url::{Url, ParseError}; use self::hyper::server::response::Response; use self::hyper::server::request::Request; use self::hyper::status::StatusCode; use self::hyper::header::Location; use self::hyper::Client; use self::hyper::error::Error as HyperError;...
} impl CasClient { /// Construct a new CasClient. The for each url except service_url, the /// \<thing\>_path is concatinated onto base_url to form the Url pub fn new(base_url: &str, login_path: &str, logout_path: &str, verify_path: &str, service...
{ VerifyError::Url(err) }
identifier_body
cas.rs
extern crate url; extern crate hyper; extern crate xml; use self::url::{Url, ParseError}; use self::hyper::server::response::Response; use self::hyper::server::request::Request; use self::hyper::status::StatusCode; use self::hyper::header::Location; use self::hyper::Client; use self::hyper::error::Error as HyperError;...
enum XmlMatchStatus { None, ExpectSuccess, } /// Errors that can happen when verifying. Xml is unlikely. #[derive(Debug)] pub enum VerifyError { Hyper(HyperError), Xml(XmlError), Url(ParseError), UnsupportedUriType, NoTicketFound, } impl From<HyperError> for VerifyError { fn from(err:...
} #[derive(Debug)]
random_line_split
gio_ext.rs
use std::ptr; use gio::{ Cancellable, SocketConnection, SocketListener, }; use gio_sys; use glib::Error; use glib::translate::{ ToGlibPtr, from_glib_full, from_glib_none, }; use glib_sys; use gobject_sys; // TODO: remove when https://github.com/gtk-rs/gio/issues/99 is fixed. pub struct Listene...
<Q: FnOnce(Result<(SocketConnection, Option<glib::Object>), Error>) + Send +'static>(_source_object: *mut gobject_sys::GObject, res: *mut gio_sys::GAsyncResult, user_data: glib_sys::gpointer) { let mut error = ptr::null_mut(); let mut source_object = ptr::null_mut(); let ret ...
accept_async_trampoline
identifier_name
gio_ext.rs
use std::ptr; use gio::{ Cancellable, SocketConnection, SocketListener, }; use gio_sys; use glib::Error; use glib::translate::{ ToGlibPtr, from_glib_full, from_glib_none, }; use glib_sys; use gobject_sys; // TODO: remove when https://github.com/gtk-rs/gio/issues/99 is fixed. pub struct Listene...
else { Err(from_glib_full(error)) }; let callback: Box<Box<Q>> = Box::from_raw(user_data as *mut _); callback(result); } let callback = accept_async_trampoline::<Q>; unsafe { gio_sys::g_socket_listener_accept_async(self.listener.to_glib_none().0, cancellable....
{ Ok((from_glib_full(ret), from_glib_none(source_object))) }
conditional_block
gio_ext.rs
use std::ptr; use gio::{ Cancellable, SocketConnection, SocketListener, }; use gio_sys; use glib::Error; use glib::translate::{ ToGlibPtr, from_glib_full, from_glib_none, }; use glib_sys; use gobject_sys; // TODO: remove when https://github.com/gtk-rs/gio/issues/99 is fixed. pub struct Listene...
let user_data: Box<Box<Q>> = Box::new(Box::new(callback)); unsafe extern "C" fn accept_async_trampoline<Q: FnOnce(Result<(SocketConnection, Option<glib::Object>), Error>) + Send +'static>(_source_object: *mut gobject_sys::GObject, res: *mut gio_sys::GAsyncResult, user_data: glib_sys::gpointer) {...
random_line_split
lib.rs
//! A Chef Client API library //! //! This library implements the raw requests and authentication methods //! necessary to interact with a [Chef] Server. //! //! See the [Chef Server API] documentation for further information on the possible requests. //! //! ## Connecting //! //! You'll need a credentials file as docu...
//! //! This crate uses [`serde`] to serialize requests from JSON. //! //! [Chef]: https://www.chef.io/chef/ //! [Chef Server API]: https://chef-server-api-docs.chef.io/ //! [RFC 99]: https://chef.github.io/chef-rfc/rfc099-authentication-config-file.html //! [`serde`]: https://serde.rs/ //! #[macro_use] extern crate f...
//! //! let client = ApiClient::from_credentials(None).unwrap(); //! let cookbooks = client.cookbooks().get(); //! ```
random_line_split
shader_param.rs
// Copyright 2015 The Gfx-rs Developers. // // 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 ag...
(cx: &mut ext::base::ExtCtxt, span: codemap::Span, name: &str, with_self: bool, declaration: P<ast::FnDecl>, body: P<ast::Block>) -> ast::ImplItem { ast::ImplItem { id: ast::DUMMY_NODE_ID, ident: cx.ident_of(name), vis: ast::Visibility::Inherited, attrs:...
impl_method
identifier_name
shader_param.rs
// Copyright 2015 The Gfx-rs Developers. // // 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 ag...
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use syntax::{abi, ast, codemap, ext}; use syntax::ext::base::ItemDecorator; use syntax::ext::build::AstBuilder; use syntax::owned_slice::O...
// distributed under the License is distributed on an "AS IS" BASIS,
random_line_split
shader_param.rs
// Copyright 2015 The Gfx-rs Developers. // // 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 ag...
node: if with_self { ast::SelfRegion(None, ast::MutImmutable, cx.ident_of("self")) } else { ast::SelfStatic }, span: span } }, body ), s...
{ ast::ImplItem { id: ast::DUMMY_NODE_ID, ident: cx.ident_of(name), vis: ast::Visibility::Inherited, attrs: Vec::new(), node: ast::MethodImplItem( ast::MethodSig { unsafety: ast::Unsafety::Normal, abi: abi::Abi::Rust, ...
identifier_body
build.rs
extern crate gcc; use std::fs; use std::env; use std::path::Path; fn target_arch_get() -> &'static str
fn build_lib_boot() { let arch = target_arch_get(); let src_dir = Path::new("src/hal/xen/boot/asm/").join(arch); gcc::compile_library("libboot.a", &[src_dir.join("boot.S").to_str().unwrap()]); } fn build_lib_switch() { let arch = target_arch_get(); let src_dir = Path::...
{ let target = env::var("TARGET").unwrap(); if target.starts_with("x86_64") { "x86_64" } else if target.starts_with("i686") { "i686" } else { panic!("Unsupported architecture: {}", target); } }
identifier_body
build.rs
extern crate gcc; use std::fs; use std::env; use std::path::Path; fn target_arch_get() -> &'static str { let target = env::var("TARGET").unwrap(); if target.starts_with("x86_64") { "x86_64" } else if target.starts_with("i686") { "i686" } else { panic!("Unsupported architecture...
(out_path: &str) { let arch = target_arch_get(); let out_dir = Path::new(&out_path); let linker_dir = Path::new("src/hal/xen/boot/asm/").join(arch); fs::copy(linker_dir.join("linker.ld"), out_dir.join("linker.ld")).unwrap(); } fn main() { let out_dir = env::var("OUT_DIR").unwrap(); build_lib_...
copy_linker_script
identifier_name
build.rs
extern crate gcc; use std::fs; use std::env; use std::path::Path; fn target_arch_get() -> &'static str { let target = env::var("TARGET").unwrap(); if target.starts_with("x86_64") { "x86_64" } else if target.starts_with("i686") { "i686" } else { panic!("Unsupported architecture...
fn build_lib_switch() { let arch = target_arch_get(); let src_dir = Path::new("src/thread/context").join(arch); gcc::compile_library("libswitch.a", &[src_dir.join("switch.S").to_str().unwrap()]); } fn copy_linker_script(out_path: &str) { let arch = target_arch_get(); let...
&[src_dir.join("boot.S").to_str().unwrap()]); }
random_line_split
backup_handler.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::{ event_store::EventStore, ledger_store::LedgerStore, metrics::{ BACKUP_EPOCH_ENDING_EPOCH, BACKUP_STATE_SNAPSHOT_LEAF_IDX, BACKUP_STATE_SNAPSHOT_VERSION, BACKUP_TXN_VERSION, }, state_store...
(&self) -> Result<Option<DbState>> { self.ledger_store .get_startup_info()? .map(|s| { Ok(DbState { epoch: s.get_epoch_state().epoch, committed_version: s .committed_tree_state .num_transa...
get_db_state
identifier_name
backup_handler.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::{ event_store::EventStore, ledger_store::LedgerStore, metrics::{ BACKUP_EPOCH_ENDING_EPOCH, BACKUP_STATE_SNAPSHOT_LEAF_IDX, BACKUP_STATE_SNAPSHOT_VERSION, BACKUP_TXN_VERSION, }, state_store...
.get_transaction_info_with_proof(version, ledger_info.ledger_info().version())?; Ok((txn_info, ledger_info)) } pub fn get_epoch_ending_ledger_info_iter( &self, start_epoch: u64, end_epoch: u64, ) -> Result<impl Iterator<Item = Result<LedgerInfoWithSignatures>> + ...
let epoch = self.ledger_store.get_epoch(version)?; let ledger_info = self.ledger_store.get_latest_ledger_info_in_epoch(epoch)?; let txn_info = self .ledger_store
random_line_split
bin.rs
#![crate_type="bin"] use std::cmp::max; use std::io; use std::iter::Repeat; fn
() { let mut reader = io::stdin(); // first line tells the height of the triangle let height = from_str::<uint>(reader.read_line().unwrap().as_slice().trim()).unwrap(); // read in triangle as vector (level-order) let triangle: Vec<uint> = reader.lines() .flat_map(|line| { line.u...
main
identifier_name
bin.rs
#![crate_type="bin"] use std::cmp::max; use std::io; use std::iter::Repeat; fn main()
.flat_map(|x| Repeat::new(x).take(x)) .collect(); // allocate solution vector let mut maxSum: Vec<uint> = Repeat::new(0u).take(triangle.len()).collect(); // find index of first leaf let last_idx = triangle.len() - height; // base case: leaves' sums are set to their value for i in...
{ let mut reader = io::stdin(); // first line tells the height of the triangle let height = from_str::<uint>(reader.read_line().unwrap().as_slice().trim()).unwrap(); // read in triangle as vector (level-order) let triangle: Vec<uint> = reader.lines() .flat_map(|line| { line.unw...
identifier_body
bin.rs
#![crate_type="bin"] use std::cmp::max; use std::io; use std::iter::Repeat; fn main() { let mut reader = io::stdin(); // first line tells the height of the triangle let height = from_str::<uint>(reader.read_line().unwrap().as_slice().trim()).unwrap(); // read in triangle as vector (level-order) ...
// allocate solution vector let mut maxSum: Vec<uint> = Repeat::new(0u).take(triangle.len()).collect(); // find index of first leaf let last_idx = triangle.len() - height; // base case: leaves' sums are set to their value for i in range(last_idx, triangle.len()) { *maxSum.get_mut(i) = t...
let heights: Vec<uint> = range(1, height + 1) .flat_map(|x| Repeat::new(x).take(x)) .collect();
random_line_split
mod.rs
// Copyright 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-MIT or ...
#[cfg(unix)] #[inline] fn retry(f: || -> libc::c_int) -> libc::c_int { loop { match f() { -1 if os::errno() as int == libc::EINTR as int => {} n => return n, } } } fn keep_going(data: &[u8], f: |*u8, uint| -> i64) -> i64 { let origamt = data.len(); let mut data...
{ loop { match f() { -1 if os::errno() as int == libc::WSAEINTR as int => {} n => return n, } } }
identifier_body
mod.rs
// Copyright 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-MIT or ...
} // windows has zero values as errors #[cfg(windows)] fn mkerr_winbool(ret: libc::c_int) -> IoResult<()> { if ret == 0 { Err(last_error()) } else { Ok(()) } } #[cfg(windows)] #[inline] fn retry(f: || -> libc::c_int) -> libc::c_int { loop { match f() { -1 if os::er...
{ Ok(()) }
conditional_block
mod.rs
// Copyright 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-MIT or ...
use std::io; use std::io::IoError; use std::io::net::ip::SocketAddr; use std::io::process::ProcessConfig; use std::io::signal::Signum; use libc::c_int; use libc; use std::os; use std::rt::rtio; use std::rt::rtio::{RtioTcpStream, RtioTcpListener, RtioUdpSocket, RtioUnixListener, RtioPipe, RtioFileStr...
use std::c_str::CString;
random_line_split
mod.rs
// Copyright 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-MIT or ...
(&mut self, path: &CString) -> IoResult<io::FileStat> { file::stat(path) } fn fs_mkdir(&mut self, path: &CString, mode: io::FilePermission) -> IoResult<()> { file::mkdir(path, mode) } fn fs_chmod(&mut self, path: &CString, mode: io::FilePermission) -> IoRe...
fs_stat
identifier_name
format.rs
// run-rustfix #![allow(clippy::print_literal, clippy::redundant_clone)] #![warn(clippy::useless_format)] struct Foo(pub String); macro_rules! foo { ($($t:tt)*) => (Foo(format!($($t)*))) } fn
() { format!("foo"); format!("{{}}"); format!("{{}} abc {{}}"); format!( r##"foo {{}} " bar"## ); format!("{}", "foo"); format!("{:?}", "foo"); // Don't warn about `Debug`. format!("{:8}", "foo"); format!("{:width$}", "foo", width = 8); format!("{:+}", "foo"); // Warn wh...
main
identifier_name
format.rs
// run-rustfix #![allow(clippy::print_literal, clippy::redundant_clone)] #![warn(clippy::useless_format)] struct Foo(pub String); macro_rules! foo { ($($t:tt)*) => (Foo(format!($($t)*))) } fn main() { format!("foo"); format!("{{}}"); format!("{{}} abc {{}}"); format!( r##"foo {{}} " bar"...
format!("prepend {:+}", "s"); }
random_line_split
blob.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::BlobBinding; use dom::bindings::codegen...
(global: GlobalRef, id: SelectedFileId) -> Result<Vec<u8>, ()> { let file_manager = global.filemanager_thread(); let (chan, recv) = ipc::channel().map_err(|_|())?; let origin = get_blob_origin(&global.get_url()); let check_url_validity = false; let msg = FileManagerThreadMsg::ReadFile(chan, id, chec...
read_file
identifier_name
blob.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::BlobBinding; use dom::bindings::codegen...
// https://w3c.github.io/FileAPI/#constructorBlob pub fn Constructor(global: GlobalRef, blobParts: Option<Vec<BlobOrString>>, blobPropertyBag: &BlobBinding::BlobPropertyBag) -> Fallible<Root<Blob>> { // TODO: accept other blobParts t...
{ let global = parent.global(); let blob_impl = match *parent.blob_impl.borrow() { BlobImpl::File(_) => { // Create new parent node BlobImpl::Sliced(JS::from_ref(parent), rel_pos) } BlobImpl::Memory(_) => { // Create new...
identifier_body
blob.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::BlobBinding; use dom::bindings::codegen...
, &BlobOrString::Blob(ref b) => { let mut bytes = b.get_bytes().unwrap_or(vec![]); ret.append(&mut bytes); }, } } Ok(ret) } impl BlobMethods for Blob { // https://w3c.github.io/FileAPI/#dfn-size fn Size(&self) -> u64 { // XXX: Thi...
{ let mut bytes = UTF_8.encode(s, EncoderTrap::Replace).map_err(|_|())?; ret.append(&mut bytes); }
conditional_block
blob.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::BlobBinding; use dom::bindings::codegen...
/// Get a FileID representing sliced parent-blob content fn create_sliced_url_id(&self, parent_id: &SelectedFileId, rel_pos: &RelativePos, parent_len: u64) -> SelectedFileId { let global = self.global(); let origin = get_blob_origin(&global.r().get_url()); ...
}
random_line_split
parser.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! The context within which CSS code is parsed. use context::QuirksMode; use cssparser::{Parser, SourceLocation,...
// XXXManishearth Replace all specified value parse impls with impls of this // trait. This will make it easy to write more generic values in the future. /// A trait to abstract parsing of a specified value given a `ParserContext` and /// CSS input. pub trait Parse : Sized { /// Parse a value of this type. //...
self.url_data.is_chrome() || self.stylesheet_origin == Origin::User } }
identifier_body
parser.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! The context within which CSS code is parsed. use context::QuirksMode; use cssparser::{Parser, SourceLocation,...
(&self) -> CssRuleType { self.rule_type.expect("Rule type expected, but none was found.") } /// Record a CSS parse error with this context’s error reporting. pub fn log_css_error<R>( &self, context: &ParserErrorContext<R>, location: SourceLocation, error: ContextualP...
rule_type
identifier_name
parser.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! The context within which CSS code is parsed. use context::QuirksMode;
use cssparser::{Parser, SourceLocation, UnicodeRange}; use error_reporting::{ParseErrorReporter, ContextualParseError}; use style_traits::{OneOrMoreSeparated, ParseError, ParsingMode, Separator}; use stylesheets::{CssRuleType, Origin, UrlExtraData, Namespaces}; /// Asserts that all ParsingMode flags have a matching Pa...
random_line_split
method.rs
use std::fmt; /// HTTP methods, as defined in RFC 2616, §5.1.1. /// /// Method names are case-sensitive. #[deriving(Eq,Clone)] pub enum Method { Options, Get, Head, Post, Put, Delete, Trace, Connect, Patch, // RFC 5789 ExtensionMethod(~str), } impl ToStr for Method { /// G...
method: &str) -> Option<Method> { assert!(method.is_ascii()); Some(match method { "OPTIONS" => Options, "GET" => Get, "HEAD" => Head, "POST" => Post, "PUT" => Put, "DELETE" => Delete, "TRACE" => Trace, ...
rom_str_or_new(
identifier_name
method.rs
use std::fmt; /// HTTP methods, as defined in RFC 2616, §5.1.1. /// /// Method names are case-sensitive. #[deriving(Eq,Clone)] pub enum Method { Options, Get, Head, Post, Put, Delete, Trace, Connect, Patch, // RFC 5789 ExtensionMethod(~str), } impl ToStr for Method { /// G...
} impl Method { /** * Get a `Method` from an *ASCII* string. * * (If the string isn't ASCII, this will at present fail.) */ pub fn from_str_or_new(method: &str) -> Option<Method> { assert!(method.is_ascii()); Some(match method { "OPTIONS" => Options, ...
}) }
random_line_split
font.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/. */ /// Implementation of Quartz (CoreGraphics) fonts. use app_units::Au; use byteorder::{BigEndian, ByteOrder}; use ...
fn glyph_h_advance(&self, glyph: GlyphId) -> Option<FractionalPixel> { let glyphs = [glyph as CGGlyph]; let advance = self.ctfont.get_advances_for_glyphs(kCTFontDefaultOrientation, &glyphs[0], ...
fn can_do_fast_shaping(&self) -> bool { self.can_do_fast_shaping }
random_line_split
font.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/. */ /// Implementation of Quartz (CoreGraphics) fonts. use app_units::Au; use byteorder::{BigEndian, ByteOrder}; use ...
fn glyph_h_advance(&self, glyph: GlyphId) -> Option<FractionalPixel> { let glyphs = [glyph as CGGlyph]; let advance = self.ctfont.get_advances_for_glyphs(kCTFontDefaultOrientation, &glyphs[0], ...
{ self.can_do_fast_shaping }
identifier_body
font.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/. */ /// Implementation of Quartz (CoreGraphics) fonts. use app_units::Au; use byteorder::{BigEndian, ByteOrder}; use ...
(&self) -> bool { self.can_do_fast_shaping } fn glyph_h_advance(&self, glyph: GlyphId) -> Option<FractionalPixel> { let glyphs = [glyph as CGGlyph]; let advance = self.ctfont.get_advances_for_glyphs(kCTFontDefaultOrientation, &gl...
can_do_fast_shaping
identifier_name
geom.rs
#[derive(Copy, Clone)] pub struct Vertex { pub position: (f32, f32, f32), } implement_vertex!(Vertex, position); #[derive(Copy, Clone)] pub struct
{ pub position: (f32, f32, f32), pub tex_coords: (f32, f32), } implement_vertex!(TexVertex, position, tex_coords); #[derive(Copy, Clone)] pub struct Normal { pub normal: (f32, f32, f32) } implement_vertex!(Normal, normal); #[derive(Copy, Clone)] pub struct Color { pub color: (f32, f32, f32)...
TexVertex
identifier_name
geom.rs
#[derive(Copy, Clone)] pub struct Vertex { pub position: (f32, f32, f32), } implement_vertex!(Vertex, position); #[derive(Copy, Clone)] pub struct TexVertex { pub position: (f32, f32, f32), pub tex_coords: (f32, f32), } implement_vertex!(TexVertex, position, tex_coords); #[derive(Copy, Clone...
normals: vec![Normal{normal: (0.0, 0.0, 0.0)}; num_vertices], colors: vec![Color{color: (0.0, 0.0, 0.0)}; num_vertices], indices: vec![0; num_indices], } }
vertices: vec![Vertex{position: (0.0, 0.0, 0.0)}; num_vertices],
random_line_split
audio-wav.rs
extern crate sdl2; use sdl2::audio::{AudioCVT, AudioCallback, AudioSpecDesired, AudioSpecWAV}; use std::borrow::Cow; use std::path::{Path, PathBuf}; use std::time::Duration; // NOTE: You probably want to investigate the // mixer feature for real use cases. struct Sound { data: Vec<u8>, volume: f32, pos: ...
spec.channels, spec.freq, ) .expect("Could not convert WAV file"); let data = cvt.convert(wav.buffer().to_vec()); // initialize the audio callback Sound { data: data, volume: 0.25, pos: 0, } })?; // Sta...
spec.format,
random_line_split
audio-wav.rs
extern crate sdl2; use sdl2::audio::{AudioCVT, AudioCallback, AudioSpecDesired, AudioSpecWAV}; use std::borrow::Cow; use std::path::{Path, PathBuf}; use std::time::Duration; // NOTE: You probably want to investigate the // mixer feature for real use cases. struct
{ data: Vec<u8>, volume: f32, pos: usize, } impl AudioCallback for Sound { type Channel = u8; fn callback(&mut self, out: &mut [u8]) { for dst in out.iter_mut() { // With channel type u8 the "silence" value is 128 (middle of the 0-2^8 range) so we need // to both f...
Sound
identifier_name
clone.rs
#![feature(core)] extern crate core; #[cfg(test)] mod tests { use core::option::Iter; // #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)] // #[stable(feature = "rust1", since = "1.0.0")] // pub enum Option<T> { // /// No value // #[stable(feature = "rust1", since = "...
#[test] fn clone_test2() { let x: Option<T> = None::<T>; let mut iter: Iter<T> = x.iter(); let mut clone: Iter<T> = iter.clone(); assert_eq!(iter.next(), None::<&T>); assert_eq!(clone.next(), None::<&T>); } }
{ let x: Option<T> = Some::<T>(68); let mut iter: Iter<T> = x.iter(); let mut clone: Iter<T> = iter.clone(); assert_eq!(iter.next(), Some::<&T>(&68)); assert_eq!(iter.next(), None::<&T>); assert_eq!(clone.next(), Some::<&T>(&68)); assert_eq!(clone.next(), None::<&T>); }
identifier_body
clone.rs
#![feature(core)] extern crate core; #[cfg(test)] mod tests { use core::option::Iter; // #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
// pub enum Option<T> { // /// No value // #[stable(feature = "rust1", since = "1.0.0")] // None, // /// Some value `T` // #[stable(feature = "rust1", since = "1.0.0")] // Some(T) // } // pub struct Iter<'a, A: 'a> { inner: Item<&'a A> } // impl<'a, A> C...
// #[stable(feature = "rust1", since = "1.0.0")]
random_line_split
clone.rs
#![feature(core)] extern crate core; #[cfg(test)] mod tests { use core::option::Iter; // #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)] // #[stable(feature = "rust1", since = "1.0.0")] // pub enum Option<T> { // /// No value // #[stable(feature = "rust1", since = "...
() { let x: Option<T> = None::<T>; let mut iter: Iter<T> = x.iter(); let mut clone: Iter<T> = iter.clone(); assert_eq!(iter.next(), None::<&T>); assert_eq!(clone.next(), None::<&T>); } }
clone_test2
identifier_name
after_render.rs
use GenericEvent; use AFTER_RENDER; /// After render arguments. #[derive(Copy, Clone, PartialEq, Debug)] pub struct AfterRenderArgs; /// After rendering and buffers are swapped. pub trait AfterRenderEvent { /// Creates an after render event. fn from_after_render_args(args: &AfterRenderArgs, old_event: &Self) ...
use std::any::Any;
random_line_split
after_render.rs
use std::any::Any; use GenericEvent; use AFTER_RENDER; /// After render arguments. #[derive(Copy, Clone, PartialEq, Debug)] pub struct AfterRenderArgs; /// After rendering and buffers are swapped. pub trait AfterRenderEvent { /// Creates an after render event. fn from_after_render_args(args: &AfterRenderArgs...
fn after_render<U, F>(&self, mut f: F) -> Option<U> where F: FnMut(&AfterRenderArgs) -> U { if self.event_id()!= AFTER_RENDER { return None; } self.with_args(|any| { if let Some(args) = any.downcast_ref::<AfterRenderArgs>() { Some(f(args)...
{ GenericEvent::from_args(AFTER_RENDER, args as &Any, old_event) }
identifier_body
after_render.rs
use std::any::Any; use GenericEvent; use AFTER_RENDER; /// After render arguments. #[derive(Copy, Clone, PartialEq, Debug)] pub struct AfterRenderArgs; /// After rendering and buffers are swapped. pub trait AfterRenderEvent { /// Creates an after render event. fn from_after_render_args(args: &AfterRenderArgs...
}) } } #[cfg(test)] mod tests { use super::*; #[test] fn test_event_after_render() { use Event; use AfterRenderArgs; let e = Event::AfterRender(AfterRenderArgs); let x: Option<Event> = AfterRenderEvent::from_after_render_args( &AfterRenderArgs, &e)...
{ panic!("Expected AfterRenderArgs") }
conditional_block
after_render.rs
use std::any::Any; use GenericEvent; use AFTER_RENDER; /// After render arguments. #[derive(Copy, Clone, PartialEq, Debug)] pub struct
; /// After rendering and buffers are swapped. pub trait AfterRenderEvent { /// Creates an after render event. fn from_after_render_args(args: &AfterRenderArgs, old_event: &Self) -> Option<Self>; /// Calls closure if this is an after render event. fn after_render<U, F>(&self, f: F) -> Option<U> ...
AfterRenderArgs
identifier_name
generated_content.rs
// Nothing to do here. } GeneratedContentInfo::ContentItem(ContentItem::Counter(ref counter_name, counter_style)) => { let temporary_counter = Counter::new(); let counter = sel...
conditional_block
generated_content.rs
�', '౨', '౩', '౪', '౫', '౬', '౭', '౮', '౯']; static THAI: [char; 10] = ['๐', '๑', '๒', '๓', '๔', '๕', '๖', '๗', '๘', '๙']; static TIBETAN: [char; 10] = ['༠', '༡', '༢', '༣', '༤', '༥', '༦', '༧', '༨', '༩']; // Alphabetic styles per CSS-COUNTER-STYLES § 6.2: static LOWER_ALPHA: [char; 26] = [ 'a', 'b', 'c', 'd', 'e', ...
-> Option<SpecificFragmentInfo> { let mut fragments = LinkedList::new();
String)
identifier_name
generated_content.rs
// Nothing to do here. } GeneratedContentInfo::ContentItem(ContentItem::Counter(ref counter_name, counter_style)) => { let temporary_counter = Counter::new(); let counter =...
value as usize }
random_line_split
mod.rs
// Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0. pub mod aggr_executor; pub mod hash_aggr_helper; #[cfg(test)] pub mod mock_executor; pub mod scan_executor; use tipb::FieldType; use tidb_query_common::Result; use tidb_query_datatype::codec::batch::LazyBatchColumnVec; use tidb_query_datatype::expr::...
/// Evaluates expressions and outputs the result into the given Vec. Lifetime of the expressions /// are erased. pub unsafe fn eval_exprs_decoded_no_lifetime<'a>( ctx: &mut EvalContext, exprs: &[RpnExpression], schema: &[FieldType], input_physical_columns: &LazyBatchColumnVec, input_logical_rows: ...
{ for expr in exprs { expr.ensure_columns_decoded(ctx, schema, input_physical_columns, input_logical_rows)?; } Ok(()) }
identifier_body
mod.rs
// Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0. pub mod aggr_executor; pub mod hash_aggr_helper; #[cfg(test)] pub mod mock_executor; pub mod scan_executor; use tipb::FieldType; use tidb_query_common::Result; use tidb_query_datatype::codec::batch::LazyBatchColumnVec; use tidb_query_datatype::expr::...
<'a, T:?Sized>(v: &T) -> &'a T { &*(v as *const T) } for expr in exprs { output.push(erase_lifetime(expr).eval_decoded( ctx, erase_lifetime(schema), erase_lifetime(input_physical_columns), erase_lifetime(input_logical_rows), input_logi...
erase_lifetime
identifier_name
mod.rs
// Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0. pub mod aggr_executor; pub mod hash_aggr_helper; #[cfg(test)]
use tidb_query_common::Result; use tidb_query_datatype::codec::batch::LazyBatchColumnVec; use tidb_query_datatype::expr::EvalContext; use tidb_query_expr::RpnExpression; use tidb_query_expr::RpnStackNode; /// Decodes all columns that are not decoded. pub fn ensure_columns_decoded( ctx: &mut EvalContext, exprs...
pub mod mock_executor; pub mod scan_executor; use tipb::FieldType;
random_line_split
modif.rs
use std::path::PathBuf; use std::fs; use clausewitz_data::{file, CwTable, CwValue}; use ::{Hoi4Country, Hoi4State, Hoi4Units}; pub struct Hoi4Mod { name: String, friendly_name: String, game_version: String, tags: Vec<String>, countries: Vec<Hoi4Country>, states: Vec<Hoi4State>, units: Vec<...
(&self) -> CwTable { let mut table = CwTable::new(); for country in &self.countries { table.set(country.tag(), format!("countries/{}.txt", country.name()).into()); } table } fn export_states(&self, path: &PathBuf) { info!("Exporting states..."); let ...
generate_country_tags_table
identifier_name
modif.rs
use std::path::PathBuf; use std::fs; use clausewitz_data::{file, CwTable, CwValue}; use ::{Hoi4Country, Hoi4State, Hoi4Units}; pub struct Hoi4Mod { name: String, friendly_name: String, game_version: String, tags: Vec<String>, countries: Vec<Hoi4Country>, states: Vec<Hoi4State>, units: Vec<...
// Get the actual directory we export to let mut dir = path.clone(); dir.push(&self.name); // Delete the old mod directory if it's already there and create a new mod folder to export to if dir.exists() { warn!("Directory already exists, deleting stale..."); ...
{ panic!("Output path does not exist!"); }
conditional_block
modif.rs
use std::path::PathBuf; use std::fs; use clausewitz_data::{file, CwTable, CwValue}; use ::{Hoi4Country, Hoi4State, Hoi4Units}; pub struct Hoi4Mod { name: String, friendly_name: String, game_version: String, tags: Vec<String>,
units: Vec<Hoi4Units>, } impl Hoi4Mod { pub fn new(name: &str, friendly_name: &str, game_version: &str) -> Self { Hoi4Mod { name: name.into(), friendly_name: friendly_name.into(), game_version: game_version.into(), tags: Vec::new(), countries...
countries: Vec<Hoi4Country>, states: Vec<Hoi4State>,
random_line_split
modif.rs
use std::path::PathBuf; use std::fs; use clausewitz_data::{file, CwTable, CwValue}; use ::{Hoi4Country, Hoi4State, Hoi4Units}; pub struct Hoi4Mod { name: String, friendly_name: String, game_version: String, tags: Vec<String>, countries: Vec<Hoi4Country>, states: Vec<Hoi4State>, units: Vec<...
pub fn add_units(&mut self, units: Hoi4Units) { self.units.push(units); } pub fn export(&self, path: &PathBuf) { info!("Exporting mod to \"{}\"...", path.display()); // Make sure the output dir exists if!path.exists() { panic!("Output path does not exist!"); ...
{ self.states.push(state); }
identifier_body
constructed.rs
use std::any::Any; use std::ops::{Deref, DerefMut}; use std::sync::{Mutex, Arc, LockResult, PoisonError, MutexGuard}; enum MaybeMutexGuardValue<'a, T: 'a> { Guard(MutexGuard<'a, T>), Ref(&'a mut T), } pub struct MaybeMutexGuard<'a, T: 'a> { inner: MaybeMutexGuardValue<'a, T>, } #[derive(Debug)] pub enum
<T> { Isolated(T), Shared(Arc<Mutex<T>>), } impl<T> Instance<T> { pub fn lock<'a>(&'a mut self) -> LockResult<MaybeMutexGuard<'a, T>> { match *self { Instance::Isolated(ref mut val) => { Ok(MaybeMutexGuard { inner: MaybeMutexGuardValue::Ref(val) }) } ...
Instance
identifier_name
constructed.rs
use std::any::Any; use std::ops::{Deref, DerefMut}; use std::sync::{Mutex, Arc, LockResult, PoisonError, MutexGuard}; enum MaybeMutexGuardValue<'a, T: 'a> { Guard(MutexGuard<'a, T>), Ref(&'a mut T), } pub struct MaybeMutexGuard<'a, T: 'a> { inner: MaybeMutexGuardValue<'a, T>, } #[derive(Debug)] pub enum ...
Shared(Box<Any>), } impl AnyInstance { pub fn downcast<T: Any>(self) -> Instance<T> { match self { AnyInstance::Isolated(parent) => { Instance::Isolated(*parent.downcast() .expect("expected AnyInstance::Isolated to downcast into type")) } ...
random_line_split
constructed.rs
use std::any::Any; use std::ops::{Deref, DerefMut}; use std::sync::{Mutex, Arc, LockResult, PoisonError, MutexGuard}; enum MaybeMutexGuardValue<'a, T: 'a> { Guard(MutexGuard<'a, T>), Ref(&'a mut T), } pub struct MaybeMutexGuard<'a, T: 'a> { inner: MaybeMutexGuardValue<'a, T>, } #[derive(Debug)] pub enum ...
} } } impl<'a, T> Deref for MaybeMutexGuard<'a, T> { type Target = T; fn deref(&self) -> &T { match self.inner { MaybeMutexGuardValue::Guard(ref val) => val, MaybeMutexGuardValue::Ref(ref val) => val, } } } impl<'a, T> DerefMut for MaybeMutexGuard<'a, ...
{ match val.lock() { Ok(guard) => Ok(MaybeMutexGuard { inner: MaybeMutexGuardValue::Guard(guard) }), Err(e) => { Err(PoisonError::new(MaybeMutexGuard { inner: MaybeMutexGuardValue::Guard(e.into_inner()), ...
conditional_block
instr_sgdt.rs
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; use ::RegType::*; use ::instruction_def::*; use ::Operand::*; use ::Reg::*; use ::RegScale::*; use ::test::run_test; #[test] fn sgdt_1() { run_test(&Instruction { mnemonic: Mnemonic::SGDT, operand1: Some(IndirectDispl...
{ run_test(&Instruction { mnemonic: Mnemonic::SGDT, operand1: Some(IndirectScaledIndexedDisplaced(RDX, RCX, Eight, 662100125, Some(OperandSize::Unsized), None)), operand2: None, operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[15, 1, 13...
identifier_body
instr_sgdt.rs
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; use ::RegType::*; use ::instruction_def::*; use ::Operand::*; use ::Reg::*; use ::RegScale::*; use ::test::run_test; #[test] fn sgdt_1() { run_test(&Instruction { mnemonic: Mnemonic::SGDT, operand1: Some(IndirectDispl...
() { run_test(&Instruction { mnemonic: Mnemonic::SGDT, operand1: Some(IndirectScaledIndexedDisplaced(RDX, RCX, Eight, 662100125, Some(OperandSize::Unsized), None)), operand2: None, operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[15, 1,...
sgdt_3
identifier_name
instr_sgdt.rs
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; use ::RegType::*; use ::instruction_def::*; use ::Operand::*; use ::Reg::*; use ::RegScale::*; use ::test::run_test;
} #[test] fn sgdt_2() { run_test(&Instruction { mnemonic: Mnemonic::SGDT, operand1: Some(IndirectScaledIndexedDisplaced(EDX, ECX, Two, 511376979, Some(OperandSize::Unsized), None)), operand2: None, operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast...
#[test] fn sgdt_1() { run_test(&Instruction { mnemonic: Mnemonic::SGDT, operand1: Some(IndirectDisplaced(BP, 47, Some(OperandSize::Unsized), None)), operand2: None, operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[15, 1, 70, 47], Operan...
random_line_split
test.rs
// Copyright 2013-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...
// Shuffle around a few input and output handles here. We're going to pass // an explicit handle into rustc to collect output messages, but we also // want to catch the error message that rustc prints when it fails. // // We take our task-local stderr (likely set by the test runner), and move /...
{ // the test harness wants its own `main` & top level functions, so // never wrap the test in `fn main() { ... }` let test = maketest(test, Some(cratename), true, as_test_harness); let input = config::Input::Str(test.to_string()); let sessopts = config::Options { maybe_sysroot: Some(env::c...
identifier_body
test.rs
// Copyright 2013-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...
} let ret = self.fold_item_recur(item); if pushed { self.names.pop(); } return ret; } }
markdown::find_testable_code(doc, &mut *self); } None => {}
random_line_split
test.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
else if!should_fail &&!out.status.success() { panic!("test executable failed:\n{:?}", str::from_utf8(&out.error)); } } } } pub fn maketest(s: &str, cratename: Option<&str>, lints: bool, dont_insert_main: bool) -> String { let mut prog = String::new(); ...
{ panic!("test executable succeeded when it should have failed"); }
conditional_block
test.rs
// Copyright 2013-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...
(&mut self, name: &str, level: u32) { if self.use_headers && level == 1 { // we use these headings as test names, so it's good if // they're valid identifiers. let name = name.chars().enumerate().map(|(i, c)| { if (i == 0 && c.is_xid_start()) || ...
register_header
identifier_name
restrictederrorinfo.rs
// Licensed under the Apache License, Version 2.0 // <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option. // All files in the project carrying such notice may not be copied, modified, or distributed // except according ...
fn GetErrorDetails( description: *mut BSTR, error: *mut HRESULT, restrictedDescription: *mut BSTR, capabilitySid: *mut BSTR, ) -> HRESULT, fn GetReference( reference: *mut BSTR, ) -> HRESULT, }}
random_line_split
tyencode.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...
ty::ReFree(ref fr) => { mywrite!(w, "f[{}|", fr.scope_id); enc_bound_region(w, cx, fr.bound_region); mywrite!(w, "]"); } ty::ReScope(nid) => { mywrite!(w, "s{}|", nid); } ty::ReStatic => { mywrite!(w, "t"); } ...
{ mywrite!(w, "B[{}|{}|{}]", node_id, index, token::get_name(name)); }
conditional_block
tyencode.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
pub fn enc_ty(w: &mut MemWriter, cx: &ctxt, t: ty::t) { match cx.abbrevs { ac_no_abbrevs => { let result_str_opt = cx.tcx.short_names_cache.borrow() .find(&t) .map(|result| { ...
{ fmt::write(&mut *w as &mut io::Writer, fmt); }
identifier_body
tyencode.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...
(w: &mut MemWriter, mt: ast::Mutability) { match mt { MutImmutable => (), MutMutable => mywrite!(w, "m"), } } fn enc_mt(w: &mut MemWriter, cx: &ctxt, mt: ty::mt) { enc_mutability(w, mt.mutbl); enc_ty(w, cx, mt.ty); } fn enc_opt<T>(w: &mut MemWriter, t: Option<T>, enc_f: |&mut MemWriter...
enc_mutability
identifier_name
tyencode.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...
} ty::ReEarlyBound(node_id, index, name) => { mywrite!(w, "B[{}|{}|{}]", node_id, index, token::get_name(name)); } ty::ReFree(ref fr) => { mywrite!(w, "f[{}|", fr.scope_id); enc_bound_regio...
match r { ty::ReLateBound(id, br) => { mywrite!(w, "b[{}|", id); enc_bound_region(w, cx, br); mywrite!(w, "]");
random_line_split
lib.rs
pub struct PascalsTriangle { rows: u32, } impl PascalsTriangle { pub fn
(row_count: u32) -> Self { PascalsTriangle { rows: row_count } } pub fn rows(&self) -> Vec<Vec<u32>> { let mut v = Vec::new(); match self.rows { 0 => return v, 1 => { v.push(vec![1]); } 2 => { v.push(vec![1]...
new
identifier_name
lib.rs
pub struct PascalsTriangle { rows: u32, } impl PascalsTriangle { pub fn new(row_count: u32) -> Self { PascalsTriangle { rows: row_count } } pub fn rows(&self) -> Vec<Vec<u32>> { let mut v = Vec::new(); match self.rows { 0 => return v, 1 => { ...
} v } }
v.push(current_row); } }
random_line_split
lib.rs
pub struct PascalsTriangle { rows: u32, } impl PascalsTriangle { pub fn new(row_count: u32) -> Self { PascalsTriangle { rows: row_count } } pub fn rows(&self) -> Vec<Vec<u32>>
.into_iter() .chain((0..lgth - 1) .into_iter() .zip((1..lgth).into_iter()) .map(|(x, y)| last_row[x] + last_row[y])) .chain(vec![1].into_iter()) ...
{ let mut v = Vec::new(); match self.rows { 0 => return v, 1 => { v.push(vec![1]); } 2 => { v.push(vec![1]); v.push(vec![1, 1]); } _ => { v.push(vec![1]); ...
identifier_body
mod.rs
pub mod install; pub mod remove; pub mod update; pub mod reinstall; use error; use config::Config; use self::install::{install, InstallOptions}; use self::remove::{remove, RemoveOptions}; use self::update::{update, UpdateOptions}; use self::reinstall::{reinstall, ReinstallOptions}; pub enum
{ Install(InstallOptions), Remove(RemoveOptions), Update(UpdateOptions), Reinstall(ReinstallOptions), } impl Command { pub fn run(&self, conf : &Config) -> Result<(), error::DottyError> { match *self { Command::Install(ref opts) => install(opts, conf), Command::Remo...
Command
identifier_name
mod.rs
pub mod install; pub mod remove; pub mod update; pub mod reinstall; use error;
use self::update::{update, UpdateOptions}; use self::reinstall::{reinstall, ReinstallOptions}; pub enum Command { Install(InstallOptions), Remove(RemoveOptions), Update(UpdateOptions), Reinstall(ReinstallOptions), } impl Command { pub fn run(&self, conf : &Config) -> Result<(), error::DottyError> ...
use config::Config; use self::install::{install, InstallOptions}; use self::remove::{remove, RemoveOptions};
random_line_split
TestNativeExpm1.rs
/* * Copyright (C) 2014 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. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by app...
// Don't edit this file! It is auto-generated by frameworks/rs/api/gen_runtime. float __attribute__((kernel)) testNativeExpm1FloatFloat(float in) { return native_expm1(in); } float2 __attribute__((kernel)) testNativeExpm1Float2Float2(float2 in) { return native_expm1(in); } float3 __attribute__((kernel)) te...
random_line_split
version.rs
use std::fmt; /// LibRaw library version. #[derive(Debug,PartialEq,Eq,PartialOrd,Ord)] pub struct Version { inner: u32, } impl Version { /// Creates a new version with the given major, minor, and patch numbers. pub fn new(major: u8, minor: u8, patch: u8) -> Version { Version { inner: (...
/// Returns the minor version number. pub fn minor(&self) -> u8 { ((self.inner & 0x00FF00) >> 8) as u8 } /// Returns the patch version number. pub fn patch(&self) -> u8 { ((self.inner & 0x0000FF) >> 0) as u8 } } impl fmt::Display for Version { fn fmt(&self, fmt: &mut fmt:...
{ ((self.inner & 0xFF0000) >> 16) as u8 }
identifier_body
version.rs
use std::fmt; /// LibRaw library version. #[derive(Debug,PartialEq,Eq,PartialOrd,Ord)] pub struct Version { inner: u32, } impl Version { /// Creates a new version with the given major, minor, and patch numbers. pub fn new(major: u8, minor: u8, patch: u8) -> Version { Version { inner: (...
() -> Version { Version { inner: unsafe { ::libraw::libraw_versionNumber() as u32 } } } #[cfg(test)] mod test { use super::*; #[test] fn it_stores_major_version() { assert_eq!(1, Version::new(1, 0, 0).major()); assert_eq!(2, Version::new(2, 0, 0).major()); } #[test...
version
identifier_name