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
main.rs
extern crate clap; extern crate rusty_post_lib; use clap::App; use clap::Arg; use rusty_post_lib::request::request::{Request, RequestConfig, HttpMethod}; fn main() { let matches = App::new("rusty-post") .version("0.1.0") .about("Make HTTP requests") .author("Jonathan Rothberg") .ar...
println!("Headers: {:?}", headers); let config = RequestConfig::new(method, &headers, data); let request = Request::new_with_config(u.into(), &config); let resp = request.request(); println!("{}", resp); } , None => {} } println!("Hell...
{ let headers = match matches.values_of("H") { Some(h) => { h.collect() }, None => Vec::new() }; let data = match matches.value_of("data") { Some(d) => { d }, ...
conditional_block
main.rs
extern crate clap; extern crate rusty_post_lib; use clap::App; use clap::Arg; use rusty_post_lib::request::request::{Request, RequestConfig, HttpMethod}; fn main()
.arg(Arg::with_name("data") .short("d") .long("data") .takes_value(true) .default_value("") ).get_matches(); match matches.value_of("url") { Some(u) => { let headers = match matches.values_of("H") { Some(h) => { ...
{ let matches = App::new("rusty-post") .version("0.1.0") .about("Make HTTP requests") .author("Jonathan Rothberg") .arg(Arg::with_name("request") .short("X") .long("request") .default_value("GET") .takes_value(tru...
identifier_body
ai.rs
use ball::Ball; use player::Player; use settings; pub struct AI { sleep_time: f64, awake_time: f64, } impl AI { pub fn new() -> AI { AI { sleep_time: 0.0, awake_time: settings::AI_AWAKE_TIME, } } pub fn update(&mut self, dt: f64, player: &mut Player, ball:...
} } }
{ self.awake_time = settings::AI_AWAKE_TIME; self.sleep_time = settings::AI_SLEEP_TIME; }
conditional_block
ai.rs
use ball::Ball; use player::Player; use settings; pub struct AI { sleep_time: f64, awake_time: f64, } impl AI { pub fn new() -> AI { AI { sleep_time: 0.0,
} pub fn update(&mut self, dt: f64, player: &mut Player, ball: &mut Ball) { let d = ball.position()[1] - player.position()[1]; let size = ball.aabb().size; if self.awake_time > 0.0 { self.awake_time -= dt; if d < -size[1] / 4.0 { player.start_mo...
awake_time: settings::AI_AWAKE_TIME, }
random_line_split
ai.rs
use ball::Ball; use player::Player; use settings; pub struct AI { sleep_time: f64, awake_time: f64, } impl AI { pub fn
() -> AI { AI { sleep_time: 0.0, awake_time: settings::AI_AWAKE_TIME, } } pub fn update(&mut self, dt: f64, player: &mut Player, ball: &mut Ball) { let d = ball.position()[1] - player.position()[1]; let size = ball.aabb().size; if self.awake_time...
new
identifier_name
complex_inner_join.rs
extern crate rustorm; extern crate uuid; extern crate chrono; extern crate rustc_serialize; use uuid::Uuid; use rustorm::query::Query; use rustorm::query::Equality; use rustorm::dao::{Dao, IsDao}; use rustorm::pool::ManagedPool; #[derive(Debug, Clone)] pub struct Photo { pub photo_id: Uuid, pub url: Option<S...
(dao: &Dao) -> Self { Photo { photo_id: dao.get("photo_id"), url: dao.get_opt("url"), } } fn to_dao(&self) -> Dao { let mut dao = Dao::new(); dao.set("photo_id", &self.photo_id); match self.url { Some(ref _value) => dao.set("url", _val...
from_dao
identifier_name
complex_inner_join.rs
extern crate rustorm; extern crate uuid; extern crate chrono; extern crate rustc_serialize; use uuid::Uuid; use rustorm::query::Query; use rustorm::query::Equality; use rustorm::dao::{Dao, IsDao}; use rustorm::pool::ManagedPool; #[derive(Debug, Clone)] pub struct Photo { pub photo_id: Uuid, pub url: Option<S...
let frag = query.build(db.as_ref()); let expected = " SELECT * FROM bazaar.product INNER JOIN bazaar.product_category\x20 ON product_category.product_id = product.product_id\x20 INNER JOIN bazaar.category\x20 ON category.category_id = product_category.category_id...
.group_by(vec!["category.name"]) .having("count(*)", Equality::GT, &1) .asc("product.name") .desc("product.created");
random_line_split
timer.rs
// Zinc, the bare metal stack for rust. // Copyright 2014 Lionel Flandrin <lionel@svkt.org> // // 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/LICENS...
timer.configure(prescale); timer } /// Configure timer registers /// TODO(simias): Only Periodic and OneShot modes are implemented so far pub fn configure(&self, prescale: u32) { // Make sure the timer is disabled before making changes. self.regs.ctl.set_taen(false); // Configure the tim...
let timer = Timer { regs: get_reg_ref(regs), wide: wide, mode: mode};
random_line_split
timer.rs
// Zinc, the bare metal stack for rust. // Copyright 2014 Lionel Flandrin <lionel@svkt.org> // // 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/LICENS...
self.regs.tailr.set_tailr(0xffffffff); // Set prescale value if!self.wide && prescale > 0xffff { panic!("prescale is too wide for this timer"); } self.regs.apr.set_psr(prescale as u32); // Timer is now configured, we can enable it self.regs.ctl.set_taen(true); } } impl timer::Ti...
{ // Make sure the timer is disabled before making changes. self.regs.ctl.set_taen(false); // Configure the timer as half-width so that we can use the prescaler self.regs.cfg.set_cfg(reg::Timer_cfg_cfg::HalfWidth); self.regs.amr .set_mr(match self.mode { Mode::OneShot => reg::Timer...
identifier_body
timer.rs
// Zinc, the bare metal stack for rust. // Copyright 2014 Lionel Flandrin <lionel@svkt.org> // // 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/LICENS...
{ Timer0, Timer1, Timer2, Timer3, Timer4, Timer5, TimerW0, TimerW1, TimerW2, TimerW3, TimerW4, TimerW5, } /// Timer modes #[derive(Clone, Copy)] pub enum Mode { /// Periodic timer loops and restarts once the timeout is reached. Periodic, /// One shot timer is disabled once the timeout is...
TimerId
identifier_name
headless.rs
use BuilderAttribs; use CreationError; use CreationError::OsError; use libc; use std::{mem, ptr}; use super::ffi; fn with_c_str<F, T>(s: &str, f: F) -> T where F: FnOnce(*const libc::c_char) -> T { use std::ffi::CString; let c_str = CString::from_slice(s.as_bytes()); f(c_str.as_slice_with_nul().as_ptr()) ...
} impl Drop for HeadlessContext { fn drop(&mut self) { unsafe { ffi::OSMesaDestroyContext(self.context) } } } unsafe impl Send for HeadlessContext {} unsafe impl Sync for HeadlessContext {}
{ }
identifier_body
headless.rs
use BuilderAttribs; use CreationError; use CreationError::OsError; use libc; use std::{mem, ptr}; use super::ffi; fn with_c_str<F, T>(s: &str, f: F) -> T where F: FnOnce(*const libc::c_char) -> T { use std::ffi::CString; let c_str = CString::from_slice(s.as_bytes()); f(c_str.as_slice_with_nul().as_ptr()) ...
ctxt } }) } pub unsafe fn make_current(&self) { let ret = ffi::OSMesaMakeCurrent(self.context, self.buffer.as_ptr() as *mut libc::c_void, 0x1401, self.width as libc::c_int, self.height as libc::c_int); if ret == 0 { panic...
{ return Err(OsError("OSMesaCreateContext failed".to_string())); }
conditional_block
headless.rs
use BuilderAttribs; use CreationError; use CreationError::OsError; use libc; use std::{mem, ptr}; use super::ffi; fn with_c_str<F, T>(s: &str, f: F) -> T where F: FnOnce(*const libc::c_char) -> T { use std::ffi::CString; let c_str = CString::from_slice(s.as_bytes()); f(c_str.as_slice_with_nul().as_ptr()) ...
pub fn new(builder: BuilderAttribs) -> Result<HeadlessContext, CreationError> { let dimensions = builder.dimensions.unwrap(); Ok(HeadlessContext { width: dimensions.0, height: dimensions.1, buffer: ::std::iter::repeat(unsafe { mem::uninitialized() }) ...
impl HeadlessContext {
random_line_split
headless.rs
use BuilderAttribs; use CreationError; use CreationError::OsError; use libc; use std::{mem, ptr}; use super::ffi; fn with_c_str<F, T>(s: &str, f: F) -> T where F: FnOnce(*const libc::c_char) -> T { use std::ffi::CString; let c_str = CString::from_slice(s.as_bytes()); f(c_str.as_slice_with_nul().as_ptr()) ...
(&mut self) { unsafe { ffi::OSMesaDestroyContext(self.context) } } } unsafe impl Send for HeadlessContext {} unsafe impl Sync for HeadlessContext {}
drop
identifier_name
main.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...
{ unsafe { let path = Path::new("libdylib.so"); let a = DynamicLibrary::open(Some(&path)).unwrap(); assert!(a.symbol::<isize>("fun1").is_ok()); assert!(a.symbol::<isize>("fun2").is_err()); assert!(a.symbol::<isize>("fun3").is_err()); assert!(a.symbol::<isize>("fun4")....
identifier_body
main.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 a = DynamicLibrary::open(Some(&path)).unwrap(); assert!(a.symbol::<isize>("fun1").is_ok()); assert!(a.symbol::<isize>("fun2").is_err()); assert!(a.symbol::<isize>("fun3").is_err()); assert!(a.symbol::<isize>("fun4").is_ok()); assert!(a.symbol::<isize>("fun5").is_ok())...
use std::path::Path; pub fn main() { unsafe { let path = Path::new("libdylib.so");
random_line_split
main.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...
() { unsafe { let path = Path::new("libdylib.so"); let a = DynamicLibrary::open(Some(&path)).unwrap(); assert!(a.symbol::<isize>("fun1").is_ok()); assert!(a.symbol::<isize>("fun2").is_err()); assert!(a.symbol::<isize>("fun3").is_err()); assert!(a.symbol::<isize>("fun4...
main
identifier_name
implicit.rs
// This example shows how to extract out details on implicit registers // being read by instructions. extern crate capstone_rust; use capstone_rust::capstone as cs; fn
() { // Buffer of code. let code = vec![0x01, 0xc0, 0xe8, 0x06, 0x00, 0x00, 0x00]; let dec = cs::Capstone::new(cs::cs_arch::CS_ARCH_X86, cs::cs_mode::CS_MODE_32).unwrap(); // Enable detail mode. This is needed if you want to get instruction details. dec.option(cs::cs_opt_type::CS_OPT_DETAIL, cs::cs...
main
identifier_name
implicit.rs
// This example shows how to extract out details on implicit registers // being read by instructions. extern crate capstone_rust; use capstone_rust::capstone as cs; fn main() { // Buffer of code. let code = vec![0x01, 0xc0, 0xe8, 0x06, 0x00, 0x00, 0x00]; let dec = cs::Capstone::new(cs::cs_arch::CS_ARCH_X...
if details.regs_write.len()!= 0 { print!(" Implicit registers written:"); for write in details.regs_write.iter() { print!(" {}", dec.reg_name(*write).unwrap()); } print!("\n"); } } }
{ print!(" Implicit registers read:"); for read in details.regs_read.iter() { // `read` is an int that correspond to an arch-specific register. In order to // get its human readable name use `reg_name`. print!(" {}", dec.reg_name(*read).unwrap());...
conditional_block
implicit.rs
// This example shows how to extract out details on implicit registers // being read by instructions. extern crate capstone_rust; use capstone_rust::capstone as cs; fn main()
print!(" {}", dec.reg_name(*read).unwrap()); } print!("\n"); } if details.regs_write.len()!= 0 { print!(" Implicit registers written:"); for write in details.regs_write.iter() { print!(" {}", dec.reg_name(*write).unwrap())...
{ // Buffer of code. let code = vec![0x01, 0xc0, 0xe8, 0x06, 0x00, 0x00, 0x00]; let dec = cs::Capstone::new(cs::cs_arch::CS_ARCH_X86, cs::cs_mode::CS_MODE_32).unwrap(); // Enable detail mode. This is needed if you want to get instruction details. dec.option(cs::cs_opt_type::CS_OPT_DETAIL, cs::cs_op...
identifier_body
implicit.rs
// This example shows how to extract out details on implicit registers // being read by instructions. extern crate capstone_rust; use capstone_rust::capstone as cs; fn main() { // Buffer of code. let code = vec![0x01, 0xc0, 0xe8, 0x06, 0x00, 0x00, 0x00]; let dec = cs::Capstone::new(cs::cs_arch::CS_ARCH_X...
} }
random_line_split
surface.rs
// Copyright 2013 The Servo Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at ...
#[cfg(target_os="linux")] pub use platform::linux::surface::NativeCompositingGraphicsContext; #[cfg(target_os="linux")] pub use platform::linux::surface::NativeGraphicsMetadata; #[cfg(target_os="linux")] pub use platform::linux::surface::NativeGraphicsMetadataDescriptor; #[cfg(target_os="linux")] pub use platform::linu...
random_line_split
range_arg.rs
use std::ops::{Range, RangeFrom, RangeTo, RangeFull}; pub struct RangeArg { pub start: usize, pub end: Option<usize>, } impl RangeArg { pub fn len(&self, len: usize) -> usize { self.end.unwrap_or(len) - self.start } } impl From<Range<usize>> for RangeArg { #[inline] fn from(r: Range<u...
#[test] fn test_s_macro() { let s: [RangeArg; 2] = s![1..3, 1]; assert!(s[0].start == 1); assert!(s[1].start == 1); assert!(s[0].end == Some(3)); assert!(s[1].end == Some(2)); assert!(s[0].len(5) == 2); assert!(s[1].len(5) == 1); }
);
random_line_split
range_arg.rs
use std::ops::{Range, RangeFrom, RangeTo, RangeFull}; pub struct RangeArg { pub start: usize, pub end: Option<usize>, } impl RangeArg { pub fn len(&self, len: usize) -> usize
} impl From<Range<usize>> for RangeArg { #[inline] fn from(r: Range<usize>) -> RangeArg { RangeArg { start: r.start, end: Some(r.end), } } } impl From<RangeFrom<usize>> for RangeArg { #[inline] fn from(r: RangeFrom<usize>) -> RangeArg { RangeArg { ...
{ self.end.unwrap_or(len) - self.start }
identifier_body
range_arg.rs
use std::ops::{Range, RangeFrom, RangeTo, RangeFull}; pub struct RangeArg { pub start: usize, pub end: Option<usize>, } impl RangeArg { pub fn len(&self, len: usize) -> usize { self.end.unwrap_or(len) - self.start } } impl From<Range<usize>> for RangeArg { #[inline] fn from(r: Range<u...
(i: usize) -> RangeArg { RangeArg { start: i, end: Some(i+1), } } } //////////////////////////////////////////////////////////////////////////////////////////////////// #[macro_export] macro_rules! s( (@as_expr $e:expr) => ($e); (@parse [$($stack:tt)*] $r:expr) => {...
from
identifier_name
root.rs
use std::ffi::CString; use std::io::Error as IoError; use std::path::Path; use libc::chdir; use libc::{c_int, c_char}; use crate::path_util::ToCString; extern { fn chroot(dir: *const c_char) -> c_int; fn pivot_root(new_root: *const c_char, put_old: *const c_char) -> c_int; } #[cfg(not(feature="containers")...
{ let c_new_root = new_root.to_cstring(); let c_put_old = put_old.to_cstring(); if unsafe { pivot_root(c_new_root.as_ptr(), c_put_old.as_ptr()) } != 0 { return Err(format!("Error pivot_root to {:?}: {}", new_root, IoError::last_os_error())); } let c_root = CString:...
identifier_body
root.rs
use std::ffi::CString; use std::io::Error as IoError; use std::path::Path; use libc::chdir; use libc::{c_int, c_char}; use crate::path_util::ToCString;
extern { fn chroot(dir: *const c_char) -> c_int; fn pivot_root(new_root: *const c_char, put_old: *const c_char) -> c_int; } #[cfg(not(feature="containers"))] pub fn temporary_change_root<P, T, F, E>(path: P, mut fun: F) -> Result<T, E> where F: FnMut() -> Result<T, E>, E: From<String>, ...
random_line_split
root.rs
use std::ffi::CString; use std::io::Error as IoError; use std::path::Path; use libc::chdir; use libc::{c_int, c_char}; use crate::path_util::ToCString; extern { fn chroot(dir: *const c_char) -> c_int; fn pivot_root(new_root: *const c_char, put_old: *const c_char) -> c_int; } #[cfg(not(feature="containers")...
if unsafe { chroot(path.to_cstring().as_ptr()) }!= 0 { return Err(format!("Error chroot to {:?}: {}", path, IoError::last_os_error()).into()); } let res = fun(); let c_pwd = CString::new(".").unwrap(); if unsafe { chroot(c_pwd.as_ptr()) }!= 0 { return Err(...
{ return Err(format!("Error chdir to root: {}", IoError::last_os_error()).into()); }
conditional_block
root.rs
use std::ffi::CString; use std::io::Error as IoError; use std::path::Path; use libc::chdir; use libc::{c_int, c_char}; use crate::path_util::ToCString; extern { fn chroot(dir: *const c_char) -> c_int; fn pivot_root(new_root: *const c_char, put_old: *const c_char) -> c_int; } #[cfg(not(feature="containers")...
(new_root: &Path, put_old: &Path) -> Result<(), String> { let c_new_root = new_root.to_cstring(); let c_put_old = put_old.to_cstring(); if unsafe { pivot_root(c_new_root.as_ptr(), c_put_old.as_ptr()) }!= 0 { return Err(format!("Error pivot_root to {:?}: {}", new_root, IoEr...
change_root
identifier_name
runner.rs
// Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0. //! Useful functions for custom test framework. //! //! See https://doc.rust-lang.org/unstable-book/language-features/custom-test-frameworks.html. use crate::test::*; use std::cell::RefCell; use std::env; /// A runner function for running general tes...
}; TestDescAndFn { desc: case.desc.clone(), testfn: f, } }) .collect(); let args = env::args().collect::<Vec<_>>(); test_main(&args, cases, None) } thread_local!(static FS: RefCell<Option<fail::FailScenario<'static>>> = RefCell:...
})), ref f => panic!("unexpected testfn {:?}", f),
random_line_split
runner.rs
// Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0. //! Useful functions for custom test framework. //! //! See https://doc.rust-lang.org/unstable-book/language-features/custom-test-frameworks.html. use crate::test::*; use std::cell::RefCell; use std::env; /// A runner function for running general tes...
; impl TestHook for Nope { fn setup(&mut self) {} fn teardown(&mut self) {} } struct CaseLifeWatcher<H: TestHook> { name: String, hook: H, } impl<H: TestHook + Send +'static> CaseLifeWatcher<H> { fn new(name: String, mut hook: H) -> CaseLifeWatcher<H> { debug!("case start"; "name" => &nam...
Nope
identifier_name
runner.rs
// Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0. //! Useful functions for custom test framework. //! //! See https://doc.rust-lang.org/unstable-book/language-features/custom-test-frameworks.html. use crate::test::*; use std::cell::RefCell; use std::env; /// A runner function for running general tes...
} struct CaseLifeWatcher<H: TestHook> { name: String, hook: H, } impl<H: TestHook + Send +'static> CaseLifeWatcher<H> { fn new(name: String, mut hook: H) -> CaseLifeWatcher<H> { debug!("case start"; "name" => &name); hook.setup(); CaseLifeWatcher { name, hook } } } impl<H: Te...
{}
identifier_body
styled.rs
use ascii_canvas::AsciiView; use std::fmt::{Debug, Formatter, Error}; use style::Style; use super::*; pub struct Styled { style: Style, content: Box<Content> } impl Styled { pub fn new(style: Style, content: Box<Content>) -> Self { Styled { style: style, content: content, ...
(&self) -> usize { self.content.min_width() } fn emit(&self, view: &mut AsciiView) { self.content.emit(&mut view.styled(self.style)) } fn into_wrap_items(self: Box<Self>, wrap_items: &mut Vec<Box<Content>>) { let style = self.style; super::into_wrap_items_map(self.conte...
min_width
identifier_name
styled.rs
use ascii_canvas::AsciiView; use std::fmt::{Debug, Formatter, Error}; use style::Style; use super::*; pub struct Styled { style: Style, content: Box<Content> } impl Styled { pub fn new(style: Style, content: Box<Content>) -> Self { Styled { style: style, content: content, ...
}
fn fmt(&self, fmt: &mut Formatter) -> Result<(), Error> { fmt.debug_struct("Styled") .field("content", &self.content) .finish() }
random_line_split
styled.rs
use ascii_canvas::AsciiView; use std::fmt::{Debug, Formatter, Error}; use style::Style; use super::*; pub struct Styled { style: Style, content: Box<Content> } impl Styled { pub fn new(style: Style, content: Box<Content>) -> Self { Styled { style: style, content: content, ...
} impl Debug for Styled { fn fmt(&self, fmt: &mut Formatter) -> Result<(), Error> { fmt.debug_struct("Styled") .field("content", &self.content) .finish() } }
{ let style = self.style; super::into_wrap_items_map(self.content, wrap_items, |item| Styled::new(style, item)) }
identifier_body
main.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 ...
.chain(Chain(Token(0), Token(1))) .chain(Chain(Token(0), Token(1))) .chain(Chain(Token(0), Token(1))) .chain(Chain(Token(0), Token(1))) .chain(Chain(Token(0), Token(1))) .chain(Chain(Token(0), Token(1))) .parse(i) .map(|(_, i)| ((), i)) }
fn test<I>(i: I) -> Result<((), I), ()> where I: Iterator<Item = i32> { Chain(Token(0), Token(1)) .chain(Chain(Token(0), Token(1))) .chain(Chain(Token(0), Token(1)))
random_line_split
main.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 ...
<I>(i: I) -> Result<((), I), ()> where I: Iterator<Item = i32> { Chain(Token(0), Token(1)) .chain(Chain(Token(0), Token(1))) .chain(Chain(Token(0), Token(1))) .chain(Chain(Token(0), Token(1))) .chain(Chain(Token(0), Token(1))) .chain(Chain(Token(0), Token(1))) .chain(Chain(...
test
identifier_name
main.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 ...
{ Chain(Token(0), Token(1)) .chain(Chain(Token(0), Token(1))) .chain(Chain(Token(0), Token(1))) .chain(Chain(Token(0), Token(1))) .chain(Chain(Token(0), Token(1))) .chain(Chain(Token(0), Token(1))) .chain(Chain(Token(0), Token(1))) .chain(Chain(Token(0), Token...
identifier_body
isaac.rs
// http://rosettacode.org/wiki/The_ISAAC_Cipher // includes the XOR version of the encryption scheme #![feature(step_by)] use std::num::Wrapping as w; const MSG :&'static str = "a Top Secret secret"; const KEY: &'static str = "this is my secret key"; #[cfg(not(test))] fn main () { let mut isaac = Isaac::new(); ...
/// XOR message fn vernam(&mut self, msg :&[u8]) -> Vec<u8> { msg.iter().map(|&b| (self.i_rand_ascii() ^ b)) .collect::<Vec<u8>>() } } #[cfg(test)] mod test { use super::{Isaac, MSG, KEY}; const ENCRIPTED: [u8; 19] = [0x1C, 0x06, 0x36, 0x19, 0x0B, 0x12, 0x60, 0x23, 0x3B...
{ (self.i_random() % 95 + 32) as u8 }
identifier_body
isaac.rs
// http://rosettacode.org/wiki/The_ISAAC_Cipher // includes the XOR version of the encryption scheme #![feature(step_by)] use std::num::Wrapping as w; const MSG :&'static str = "a Top Secret secret"; const KEY: &'static str = "this is my secret key"; #[cfg(not(test))] fn main () { let mut isaac = Isaac::new(); ...
mix_v!(a_v); for j in 0..8 { self.mm[i+j] = a_v[j]; } } if flag { // do a second pass to make all of the seed affect all of mm for i in (0..256).step_by(8) { for j in 0..8 { a_v[j] = a_v[j] + self.mm[i+j]; } mix_v!(a_v); ...
{ // use all the information in the seed for j in 0..8 { a_v[j] = a_v[j] + self.rand_rsl[i+j]; } }
conditional_block
isaac.rs
// http://rosettacode.org/wiki/The_ISAAC_Cipher // includes the XOR version of the encryption scheme #![feature(step_by)] use std::num::Wrapping as w; const MSG :&'static str = "a Top Secret secret"; const KEY: &'static str = "this is my secret key"; #[cfg(not(test))] fn main () { let mut isaac = Isaac::new(); ...
(&mut self, seed: &str, flag: bool) { for i in 0..256 { self.mm[i] = w(0); } for i in 0..256 { self.rand_rsl[i] = w(0); } for i in 0..seed.len() { self.rand_rsl[i] = w(seed.as_bytes()[i] as u32); } // initialize ISAAC with seed self.rand_init(flag); } ...
seed
identifier_name
isaac.rs
// http://rosettacode.org/wiki/The_ISAAC_Cipher // includes the XOR version of the encryption scheme #![feature(step_by)] use std::num::Wrapping as w; const MSG :&'static str = "a Top Secret secret"; const KEY: &'static str = "this is my secret key"; #[cfg(not(test))] fn main () { let mut isaac = Isaac::new(); ...
for (a, b) in encr.iter().zip(ENCRIPTED.iter()) { assert_eq!(a, b); } } #[test] fn decrypt() { let expected = MSG; let mut isaac = Isaac::new(); isaac.seed(KEY, true); let decr = isaac.vernam(&ENCRIPTED[..]); for (&a, b) in decr.iter()....
isaac.seed(KEY, true); let encr = isaac.vernam(MSG.as_bytes());
random_line_split
lib.rs
#![feature(libc)] extern crate estimate_pi; use estimate_pi::estimate; #[cfg(not(target_os = "emscripten"))] use estimate_pi::ws; extern crate libc; use libc::{c_double}; #[no_mangle] pub extern "C" fn pi_est(points: c_double) -> c_double { estimate(points) } #[cfg(not(target_os = "emscripten"))] #[no_mangle] pu...
let pi = ws_pi_est(1e6); assert!((pi > 2.64) && (pi < 3.64), "estimated pi value is more than 0.5 off"); } }
#[test] fn ws_pi_est_test() {
random_line_split
lib.rs
#![feature(libc)] extern crate estimate_pi; use estimate_pi::estimate; #[cfg(not(target_os = "emscripten"))] use estimate_pi::ws; extern crate libc; use libc::{c_double}; #[no_mangle] pub extern "C" fn
(points: c_double) -> c_double { estimate(points) } #[cfg(not(target_os = "emscripten"))] #[no_mangle] pub extern "C" fn ws_pi_est(points: c_double) -> c_double { ws::estimate(points) } #[cfg(test)] mod pi_est_tests { use pi_est; #[test] fn pi_est_test() { let pi = pi_est(1e6); assert!((pi > 2.64) ...
pi_est
identifier_name
lib.rs
#![feature(libc)] extern crate estimate_pi; use estimate_pi::estimate; #[cfg(not(target_os = "emscripten"))] use estimate_pi::ws; extern crate libc; use libc::{c_double}; #[no_mangle] pub extern "C" fn pi_est(points: c_double) -> c_double
#[cfg(not(target_os = "emscripten"))] #[no_mangle] pub extern "C" fn ws_pi_est(points: c_double) -> c_double { ws::estimate(points) } #[cfg(test)] mod pi_est_tests { use pi_est; #[test] fn pi_est_test() { let pi = pi_est(1e6); assert!((pi > 2.64) && (pi < 3.64), "estimated pi value is more than 0.5 ...
{ estimate(points) }
identifier_body
while-prelude-drop.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 mut i = 0; // The auto slot for the result of make(i) should not leak. while make(i)!= a { i += 1; } }
main
identifier_name
while-prelude-drop.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 mut i = 0; // The auto slot for the result of make(i) should not leak. while make(i) != a { i += 1; } }
identifier_body
while-prelude-drop.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 mut s = ~"hello"; // Ensure s is non-const. s += ~"there"; return b(s); } pub fn main() { let mut i = 0; // The auto slot for the result of make(i) should not leak. while make(i)!= a { i += 1; } }
{ return a; }
conditional_block
while-prelude-drop.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(Eq)] en...
random_line_split
lib.rs
use formats::{match_name, Format}; use once_cell::sync::Lazy; use parser::{ eyre::{bail, Result}, graph_triples::{Resource, ResourceInfo}, ParserTrait, }; use std::collections::BTreeMap; use std::sync::Arc; // Re-exports pub use parser::Parser; // The following high level functions hide the implementation...
impl Run for List { async fn run(&self) -> Result { let list = PARSERS.list(); result::value(list) } } /// Show the specifications of a parser #[derive(Debug, StructOpt)] #[structopt( setting = structopt::clap::AppSettings::ColoredHelp )] pub ...
pub struct List {} #[async_trait]
random_line_split
lib.rs
use formats::{match_name, Format}; use once_cell::sync::Lazy; use parser::{ eyre::{bail, Result}, graph_triples::{Resource, ResourceInfo}, ParserTrait, }; use std::collections::BTreeMap; use std::sync::Arc; // Re-exports pub use parser::Parser; // The following high level functions hide the implementation...
), ( relations::uses((1, 8, 1, 9)), resources::symbol(&path, "a", "Number") ) ] ); Ok(()) } }
{ let path = PathBuf::from("<test>"); let resource = resources::code(&path, "<id>", "<cli>", Some("Calc".to_string())); let resource_info = parse(resource, "a = 1\nb = a * a")?; assert!(matches!(resource_info.execute_pure, None)); assert!(!resource_info.is_pure()); assert...
identifier_body
lib.rs
use formats::{match_name, Format}; use once_cell::sync::Lazy; use parser::{ eyre::{bail, Result}, graph_triples::{Resource, ResourceInfo}, ParserTrait, }; use std::collections::BTreeMap; use std::sync::Arc; // Re-exports pub use parser::Parser; // The following high level functions hide the implementation...
{} #[async_trait] impl Run for List { async fn run(&self) -> Result { let list = PARSERS.list(); result::value(list) } } /// Show the specifications of a parser #[derive(Debug, StructOpt)] #[structopt( setting = structopt::clap::AppSettings::Colo...
List
identifier_name
lib.rs
use formats::{match_name, Format}; use once_cell::sync::Lazy; use parser::{ eyre::{bail, Result}, graph_triples::{Resource, ResourceInfo}, ParserTrait, }; use std::collections::BTreeMap; use std::sync::Arc; // Re-exports pub use parser::Parser; // The following high level functions hide the implementation...
else { bail!("Attempting to parse a resource that is not a `Code` resource") }; let format = match_name(&language); let resource_info = if let Some(result) = dispatch_builtins!(format, parse, resource, &path, code) { result? } else { ...
{ (code.path.clone(), code.language.clone().unwrap_or_default()) }
conditional_block
comment.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
use crate::dom::bindings::codegen::Bindings::WindowBinding::WindowMethods; use crate::dom::bindings::error::Fallible; use crate::dom::bindings::root::DomRoot; use crate::dom::bindings::str::DOMString; use crate::dom::characterdata::CharacterData; use crate::dom::document::Document; use crate::dom::node::Node; use crate...
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::codegen::Bindings::CommentBinding;
random_line_split
comment.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 crate::dom::bindings::codegen::Bindings::CommentBinding; use crate::dom::bindings::codegen::Bindings::WindowBi...
(text: DOMString, document: &Document) -> DomRoot<Comment> { Node::reflect_node( Box::new(Comment::new_inherited(text, document)), document, CommentBinding::Wrap, ) } pub fn Constructor(window: &Window, data: DOMString) -> Fallible<DomRoot<Comment>> { ...
new
identifier_name
craft_output_metadata.rs
use rustc_serialize::{Encodable, Encoder}; use ops; use package::Package; use package_id::PackageId; use resolver::Resolve; use util::CraftResult; use workspace::Workspace; const VERSION: u32 = 1; pub struct OutputMetadataOptions { pub features: Vec<String>, pub no_default_features: bool, pub all_feature...
} let encodable = EncodableResolve { root: self.root.as_ref(), nodes: self.resolve .iter() .map(|id| { Node { id: id, dependencies: self.resolve.deps(id).collect(), ...
id: &'a PackageId, dependencies: Vec<&'a PackageId>,
random_line_split
craft_output_metadata.rs
use rustc_serialize::{Encodable, Encoder}; use ops; use package::Package; use package_id::PackageId; use resolver::Resolve; use util::CraftResult; use workspace::Workspace; const VERSION: u32 = 1; pub struct OutputMetadataOptions { pub features: Vec<String>, pub no_default_features: bool, pub all_feature...
<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> { #[derive(RustcEncodable)] struct EncodableResolve<'a> { root: Option<&'a PackageId>, nodes: Vec<Node<'a>>, } #[derive(RustcEncodable)] struct Node<'a> { id: &'a PackageId, de...
encode
identifier_name
craft_output_metadata.rs
use rustc_serialize::{Encodable, Encoder}; use ops; use package::Package; use package_id::PackageId; use resolver::Resolve; use util::CraftResult; use workspace::Workspace; const VERSION: u32 = 1; pub struct OutputMetadataOptions { pub features: Vec<String>, pub no_default_features: bool, pub all_feature...
if opt.no_deps { metadata_no_deps(ws, opt) } else { metadata_full(ws, opt) } } fn metadata_no_deps(ws: &Workspace, _opt: &OutputMetadataOptions) -> CraftResult<ExportInfo> { Ok(ExportInfo { packages: ws.members().cloned().collect(), workspace_members: ws.members().map(|...
{ bail!("metadata version {} not supported, only {} is currently supported", opt.version, VERSION); }
conditional_block
p065.rs
//! [Problem 65](https://projecteuler.net/problem=65) solver. #![warn( bad_style, unused, unused_extern_crates, unused_import_braces, unused_qualifications, unused_results )] use num_bigint::BigUint; fn
(i: u32) -> u32 { match i { 0 => 2, i if i % 3 == 2 => 2 * (i + 1) / 3, _ => 1, } } fn solve() -> String { let len = 100; let napier = (0u32..len).map(napier_seq); let (n, _d) = cont_frac::fold::<BigUint, _>(napier); n.to_string() .chars() .filter_map(|c| c...
napier_seq
identifier_name
p065.rs
//! [Problem 65](https://projecteuler.net/problem=65) solver. #![warn( bad_style, unused, unused_extern_crates, unused_import_braces, unused_qualifications, unused_results )] use num_bigint::BigUint; fn napier_seq(i: u32) -> u32 { match i { 0 => 2, i if i % 3 == 2 => 2 * (...
.to_string() } common::problem!("272", solve);
.sum::<u32>()
random_line_split
p065.rs
//! [Problem 65](https://projecteuler.net/problem=65) solver. #![warn( bad_style, unused, unused_extern_crates, unused_import_braces, unused_qualifications, unused_results )] use num_bigint::BigUint; fn napier_seq(i: u32) -> u32 { match i { 0 => 2, i if i % 3 == 2 => 2 * (...
common::problem!("272", solve);
{ let len = 100; let napier = (0u32..len).map(napier_seq); let (n, _d) = cont_frac::fold::<BigUint, _>(napier); n.to_string() .chars() .filter_map(|c| c.to_digit(10)) .sum::<u32>() .to_string() }
identifier_body
source.rs
use std::ffi::{OsStr}; use std::path::{Path}; use clang::*; use clang::source::*; pub fn test(clang: &Clang) { // File ______________________________________ super::with_file(&clang, "int a = 322;", |_, f| { #[cfg(feature="clang_6_0")] fn test_get_contents(file: &File) { assert_eq...
} #[cfg(not(feature="clang_4_0"))] fn test_get_skipped_ranges<'tu>(tu: TranslationUnit<'tu>, f: &Path) { let file = tu.get_file(f).unwrap(); assert_eq!(file.get_skipped_ranges(), &[range!(file, 2, 10, 4, 15)]); } test_get_skipped_ranges(tu, f); }); ...
{ assert_eq!(tu.get_skipped_ranges(), &[range!(file, 2, 10, 4, 15)]); assert_eq!(file.get_skipped_ranges(), &[range!(file, 2, 10, 4, 15)]); }
conditional_block
source.rs
use std::ffi::{OsStr}; use std::path::{Path}; use clang::*; use clang::source::*; pub fn test(clang: &Clang) { // File ______________________________________ super::with_file(&clang, "int a = 322;", |_, f| { #[cfg(feature="clang_6_0")] fn test_get_contents(file: &File) { assert_eq...
test_get_skipped_ranges(tu, f); }); super::with_file(&clang, "#ifndef _TEST_H_\n#define _TEST_H_\nint a = 322;\n#endif", |_, f| { assert!(f.is_include_guarded()); }); let source = r#" void f() { int a = 2 + 2; double b = 0.25 * 2.0; const c...
{ let file = tu.get_file(f).unwrap(); assert_eq!(file.get_skipped_ranges(), &[range!(file, 2, 10, 4, 15)]); }
identifier_body
source.rs
use std::ffi::{OsStr}; use std::path::{Path}; use clang::*; use clang::source::*; pub fn
(clang: &Clang) { // File ______________________________________ super::with_file(&clang, "int a = 322;", |_, f| { #[cfg(feature="clang_6_0")] fn test_get_contents(file: &File) { assert_eq!(file.get_contents(), Some("int a = 322;".into())); } #[cfg(not(feature="clan...
test
identifier_name
source.rs
use std::ffi::{OsStr}; use std::path::{Path}; use clang::*; use clang::source::*; pub fn test(clang: &Clang) { // File ______________________________________ super::with_file(&clang, "int a = 322;", |_, f| { #[cfg(feature="clang_6_0")] fn test_get_contents(file: &File) { assert_eq...
assert!(f.get_time()!= 0); super::with_file(&clang, "int a = 322;", |_, g| assert!(f.get_id()!= g.get_id())); assert_eq!(f.get_skipped_ranges(), &[]); assert!(!f.is_include_guarded()); }); let source = " #if 0 int skipped = 32; #endif int unskippe...
test_get_contents(&f); }); super::with_file(&clang, "int a = 322;", |p, f| { assert_eq!(f.get_path(), p.to_path_buf());
random_line_split
path.rs
use fnv; use super::Entry; #[derive(Debug, Clone)] pub struct Path { pub src: u32, pub dst: u32, pub path: Result<Vec<u32>,PathError>, } #[derive(Debug, Clone)] pub enum PathError { NoSuchPath, Terminated(u32) } impl Path { pub fn len(&self) -> Option<usize> { if let Ok(ref v) = self....
}, Err(PathError::NoSuchPath) => println!("\tNo such path exists"), Err(PathError::Terminated(i)) => println!("\tSearch expired after {} iterations", i), } println!("\tlen = {:?}", self.len()); } }
println!("\t{}:\t\"{}\"", i, entries[i].title);
random_line_split
path.rs
use fnv; use super::Entry; #[derive(Debug, Clone)] pub struct Path { pub src: u32, pub dst: u32, pub path: Result<Vec<u32>,PathError>, } #[derive(Debug, Clone)] pub enum PathError { NoSuchPath, Terminated(u32) } impl Path { pub fn len(&self) -> Option<usize> { if let Ok(ref v) = self....
else { None } } pub fn is_empty(&self) -> bool { if let Ok(ref v) = self.path { v.len() <= 1 } else { false } } pub fn print(&self, entries: &fnv::FnvHashMap<u32,Entry>) { println!("Path from {}\t(\"{}\")", self.src, entries.ge...
{ Some(v.len()-1) }
conditional_block
path.rs
use fnv; use super::Entry; #[derive(Debug, Clone)] pub struct
{ pub src: u32, pub dst: u32, pub path: Result<Vec<u32>,PathError>, } #[derive(Debug, Clone)] pub enum PathError { NoSuchPath, Terminated(u32) } impl Path { pub fn len(&self) -> Option<usize> { if let Ok(ref v) = self.path { Some(v.len()-1) } else { Non...
Path
identifier_name
matrix.rs
use num::{Zero,One}; use num::{Num,Float}; use std::fmt; use std::ops::{Index,IndexMut,Add,Mul,Div,Sub,Range}; use alg::Vector; /// Represents a simple `NxM` matrix. #[derive(Clone,PartialEq,Debug)] pub struct Matrix<T> { /// Number of rows (max Y) pub m: usize, /// Number of columns (max X) pub n: us...
(n: usize, m: usize) -> Self { Matrix::new(n,m, |_,_| T::zero()) } } impl <T: Clone> Matrix<T> { /// Returns a new Vector, cloned from the given row. pub fn row(&self, y: usize) -> Vector<T> { Vector::new(self.n, |i| self[(i,y)].clone()) } /// Returns a new Vector, cloned from the...
zero
identifier_name
matrix.rs
use num::{Zero,One}; use num::{Num,Float}; use std::fmt; use std::ops::{Index,IndexMut,Add,Mul,Div,Sub,Range}; use alg::Vector; /// Represents a simple `NxM` matrix. #[derive(Clone,PartialEq,Debug)] pub struct Matrix<T> { /// Number of rows (max Y) pub m: usize, /// Number of columns (max X) pub n: us...
for x in 0..self.n { self.swap((x,ya),(x,yb)); } } } impl <T: Zero> Matrix<T> { /// Creates a new matrix initialized to zero. pub fn zero(n: usize, m: usize) -> Self { Matrix::new(n,m, |_,_| T::zero()) } } impl <T: Clone> Matrix<T> { /// Returns a new Vector,...
{ return; }
conditional_block
matrix.rs
use num::{Zero,One}; use num::{Num,Float}; use std::fmt; use std::ops::{Index,IndexMut,Add,Mul,Div,Sub,Range}; use alg::Vector; /// Represents a simple `NxM` matrix. #[derive(Clone,PartialEq,Debug)] pub struct Matrix<T> { /// Number of rows (max Y) pub m: usize, /// Number of columns (max X) pub n: us...
} impl <T: Clone + Num> Matrix<T> { /// Returns the square norm of a matrix: the sum of the square of all cells. pub fn square_norm(&self) -> T { self.data.iter().map(|a| a.clone() * a.clone()).fold(T::zero(), |a,b| a+b) } /// Returns the matrix determinant. /// /// Returns zero for n...
{ Matrix::scalar(n, T::one()) }
identifier_body
matrix.rs
use num::{Zero,One}; use num::{Num,Float}; use std::fmt; use std::ops::{Index,IndexMut,Add,Mul,Div,Sub,Range}; use alg::Vector; /// Represents a simple `NxM` matrix. #[derive(Clone,PartialEq,Debug)] pub struct Matrix<T> { /// Number of rows (max Y) pub m: usize, /// Number of columns (max X) pub n: us...
let mut m = Matrix::zero(n,n); for (i,x) in vector.into_iter().enumerate() { m[(i,i)] = x; } m } /// Creates a new scalar matrix with the given value. pub fn scalar(n: usize, value: T) -> Self { Matrix::diagonal(Vector::from_copies(n, value)) } } imp...
pub fn diagonal(vector: Vector<T>) -> Self { let n = vector.dim();
random_line_split
caa.rs
use std::ffi::CStr; use std::fmt; use std::marker::PhantomData; use std::os::raw::{c_char, c_int, c_uchar, c_void}; use std::ptr; use std::slice; use itertools::Itertools; use crate::error::{Error, Result}; use crate::panic; /// The result of a successful CAA lookup. #[derive(Debug)] pub struct CAAResults { caa_...
(caa_reply: *mut c_ares_sys::ares_caa_reply) -> Self { CAAResults { caa_reply, phantom: PhantomData, } } /// Returns an iterator over the `CAAResult` values in this `CAAResults`. pub fn iter(&self) -> CAAResultsIter { CAAResultsIter { next: unsafe...
new
identifier_name
caa.rs
use std::ffi::CStr; use std::fmt; use std::marker::PhantomData; use std::os::raw::{c_char, c_int, c_uchar, c_void}; use std::ptr; use std::slice; use itertools::Itertools; use crate::error::{Error, Result}; use crate::panic; /// The result of a successful CAA lookup. #[derive(Debug)] pub struct CAAResults { caa_...
else { Err(Error::from(parse_status)) } } fn new(caa_reply: *mut c_ares_sys::ares_caa_reply) -> Self { CAAResults { caa_reply, phantom: PhantomData, } } /// Returns an iterator over the `CAAResult` values in this `CAAResults`. pub fn ite...
{ let caa_result = CAAResults::new(caa_reply); Ok(caa_result) }
conditional_block
caa.rs
use std::ffi::CStr; use std::fmt; use std::marker::PhantomData; use std::os::raw::{c_char, c_int, c_uchar, c_void}; use std::ptr; use std::slice; use itertools::Itertools; use crate::error::{Error, Result}; use crate::panic; /// The result of a successful CAA lookup. #[derive(Debug)] pub struct CAAResults { caa_...
/// Iterator of `CAAResult`s. #[derive(Clone, Copy)] pub struct CAAResultsIter<'a> { next: Option<&'a c_ares_sys::ares_caa_reply>, } impl<'a> Iterator for CAAResultsIter<'a> { type Item = CAAResult<'a>; fn next(&mut self) -> Option<Self::Item> { let opt_reply = self.next; self.next = opt_r...
let results = self.iter().format("}, {"); write!(fmt, "[{{{}}}]", results) } }
random_line_split
batch.rs
use snowchains::app::{App, Modify, Opt}; use snowchains::errors::{JudgeError, JudgeErrorKind}; use snowchains::path::AbsPathBuf; use snowchains::service::ServiceName; use snowchains::terminal::{AnsiColorChoice, Term, TermImpl}; use snowchains::testsuite::SuiteFileExtension; use failure::Fallible; use if_chain::if_chai...
if let JudgeErrorKind::Build {.. } = ctx.get_context(); then {} else { return Err(err.into()) } } if_chain! { let err = app.test(&src_path, WRONG_CODE).unwrap_err(); if let snowchains::Error::Judge(JudgeError::Context(ctx)) = &err; if let JudgeErrorKind::TestFailed(2, 2)...
app.test(&src_path, CODE)?; if_chain! { let err = app.test(&src_path, INVLID_CODE).unwrap_err(); if let snowchains::Error::Judge(JudgeError::Context(ctx)) = &err;
random_line_split
batch.rs
use snowchains::app::{App, Modify, Opt}; use snowchains::errors::{JudgeError, JudgeErrorKind}; use snowchains::path::AbsPathBuf; use snowchains::service::ServiceName; use snowchains::terminal::{AnsiColorChoice, Term, TermImpl}; use snowchains::testsuite::SuiteFileExtension; use failure::Fallible; use if_chain::if_chai...
(&mut self, timelimit: Duration) -> snowchains::Result<()> { self.run(Opt::Modify(Modify::Timelimit { service: Some(ServiceName::Atcoder), contest: Some("practice".to_owned()), color_choice: AnsiColorChoice::Never, problem: "a".to_owned(), extension: S...
modify_timelimit
identifier_name
batch.rs
use snowchains::app::{App, Modify, Opt}; use snowchains::errors::{JudgeError, JudgeErrorKind}; use snowchains::path::AbsPathBuf; use snowchains::service::ServiceName; use snowchains::terminal::{AnsiColorChoice, Term, TermImpl}; use snowchains::testsuite::SuiteFileExtension; use failure::Fallible; use if_chain::if_chai...
}
{ self.run(Opt::Modify(Modify::Timelimit { service: Some(ServiceName::Atcoder), contest: Some("practice".to_owned()), color_choice: AnsiColorChoice::Never, problem: "a".to_owned(), extension: SuiteFileExtension::Yaml, timelimit: Some(timeli...
identifier_body
tooltip.rs
// This file was generated by gir (b7f5189) from gir-files (71d73f0) // DO NOT EDIT use Widget; use ffi; use gdk; use gdk_pixbuf; use glib::object::IsA; use glib::translate::*; glib_wrapper! { pub struct Tooltip(Object<ffi::GtkTooltip>); match fn { get_type => || ffi::gtk_tooltip_get_type(), } } ...
<'a, T: Into<Option<&'a str>>>(&self, text: T) { unsafe { ffi::gtk_tooltip_set_text(self.to_glib_none().0, text.into().to_glib_none().0); } } pub fn set_tip_area(&self, rect: &gdk::Rectangle) { unsafe { ffi::gtk_tooltip_set_tip_area(self.to_glib_none().0, rect.to...
set_text
identifier_name
tooltip.rs
// This file was generated by gir (b7f5189) from gir-files (71d73f0) // DO NOT EDIT use Widget; use ffi; use gdk; use gdk_pixbuf; use glib::object::IsA; use glib::translate::*; glib_wrapper! { pub struct Tooltip(Object<ffi::GtkTooltip>); match fn { get_type => || ffi::gtk_tooltip_get_type(), } } ...
pub fn set_text<'a, T: Into<Option<&'a str>>>(&self, text: T) { unsafe { ffi::gtk_tooltip_set_text(self.to_glib_none().0, text.into().to_glib_none().0); } } pub fn set_tip_area(&self, rect: &gdk::Rectangle) { unsafe { ffi::gtk_tooltip_set_tip_area(self.to_g...
{ unsafe { ffi::gtk_tooltip_set_markup(self.to_glib_none().0, markup.into().to_glib_none().0); } }
identifier_body
tooltip.rs
// This file was generated by gir (b7f5189) from gir-files (71d73f0) // DO NOT EDIT use Widget; use ffi; use gdk; use gdk_pixbuf; use glib::object::IsA; use glib::translate::*; glib_wrapper! { pub struct Tooltip(Object<ffi::GtkTooltip>); match fn { get_type => || ffi::gtk_tooltip_get_type(), } } ...
} } pub fn set_tip_area(&self, rect: &gdk::Rectangle) { unsafe { ffi::gtk_tooltip_set_tip_area(self.to_glib_none().0, rect.to_glib_none().0); } } pub fn trigger_tooltip_query(display: &gdk::Display) { assert_initialized_main_thread!(); unsafe { ...
pub fn set_text<'a, T: Into<Option<&'a str>>>(&self, text: T) { unsafe { ffi::gtk_tooltip_set_text(self.to_glib_none().0, text.into().to_glib_none().0);
random_line_split
system_clock_pt.rs
// Zinc, the bare metal stack for rust. // Copyright 2014 Vladimir "farcaller" Pouzanov <farcaller@gmail.com> // // 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.o...
}, other => { source_freq = 0; cx.span_err( node.get_attr("source").value_span, format!("unknown oscillator value `{}`", other).as_slice()); "BAD".to_string() }, }); let some_pll_conf = node.get_by_path("pll").and_then(|sub| -> Option<(uint, uint, uint)> { ...
source_freq = some_source_frequency.unwrap(); format!("system_clock::Main({})", source_freq) }
random_line_split
system_clock_pt.rs
// Zinc, the bare metal stack for rust. // Copyright 2014 Vladimir "farcaller" Pouzanov <farcaller@gmail.com> // // 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.o...
#[test] fn fails_to_parse_bad_clock_conf() { fails_to_build("lpc17xx@mcu { clock { no_source = 1; source_frequency = 12_000_000; }}"); fails_to_build("lpc17xx@mcu { clock { source = \"missing\"; source_frequency = 12_000_000; }}"); } #[test] fn fails_to_parse_no_pll_...
{ with_parsed(" clock { source = \"main-oscillator\"; source_frequency = 12_000_000; pll { m = 50; n = 3; divisor = 4; } }", |cx, _, pt| { let mut builder = Builder::new(pt.clone()); let node = pt.get_by_path("clock").unwrap(); ...
identifier_body
system_clock_pt.rs
// Zinc, the bare metal stack for rust. // Copyright 2014 Vladimir "farcaller" Pouzanov <farcaller@gmail.com> // // 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.o...
() { with_parsed(" clock { source = \"main-oscillator\"; source_frequency = 12_000_000; pll { m = 50; n = 3; divisor = 4; } }", |cx, failed, pt| { let mut builder = Builder::new(pt.clone()); super::build_clock(&mut builder, cx, pt...
builds_clock_init
identifier_name
system_clock_pt.rs
// Zinc, the bare metal stack for rust. // Copyright 2014 Vladimir "farcaller" Pouzanov <farcaller@gmail.com> // // 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.o...
else { let m = sub.get_int_attr("m").unwrap(); let n = sub.get_int_attr("n").unwrap(); let divisor = sub.get_int_attr("divisor").unwrap(); Some((m, n, divisor)) } }); if some_pll_conf.is_none() { cx.parse_sess().span_diagnostic.span_err(node.name_span, "required subnode `pll...
{ None }
conditional_block
build.rs
use std::env; fn main() { let target_os = env::var("CARGO_CFG_TARGET_OS").unwrap(); let weak_linkage = match env::var("CARGO_FEATURE_WEAK_LINKAGE") { Ok(_) => true, Err(_) => false, }; if weak_linkage { if target_os == "linux" { println!("cargo:rustc-cdylib-link-arg...
println!("cargo:rustc-cdylib-link-arg=-Wl,-rpath,{}/../lldb/lib", origin); // Relative to target/debug/deps/ - for `cargo test` println!("cargo:rustc-cdylib-link-arg=-Wl,-rpath,{}/../../../lldb/lib", origin); } } }
} else { if target_os == "linux" || target_os == "macos" { #[rustfmt::skip] let origin = if target_os == "linux" { "$ORIGIN" } else { "@loader_path" }; // Relative to adapter/
random_line_split
build.rs
use std::env; fn
() { let target_os = env::var("CARGO_CFG_TARGET_OS").unwrap(); let weak_linkage = match env::var("CARGO_FEATURE_WEAK_LINKAGE") { Ok(_) => true, Err(_) => false, }; if weak_linkage { if target_os == "linux" { println!("cargo:rustc-cdylib-link-arg=-Wl,-Bstatic"); ...
main
identifier_name
build.rs
use std::env; fn main()
// Relative to adapter/ println!("cargo:rustc-cdylib-link-arg=-Wl,-rpath,{}/../lldb/lib", origin); // Relative to target/debug/deps/ - for `cargo test` println!("cargo:rustc-cdylib-link-arg=-Wl,-rpath,{}/../../../lldb/lib", origin); } } }
{ let target_os = env::var("CARGO_CFG_TARGET_OS").unwrap(); let weak_linkage = match env::var("CARGO_FEATURE_WEAK_LINKAGE") { Ok(_) => true, Err(_) => false, }; if weak_linkage { if target_os == "linux" { println!("cargo:rustc-cdylib-link-arg=-Wl,-Bstatic"); ...
identifier_body
main.rs
#![feature(iter_max_by, iter_min_by)] use std::collections::HashMap; use std::io; use std::io::prelude::*; enum DecodingMethod { MostLikely, LeastLikely, } fn decode_message(input: &str, method: DecodingMethod) -> String
} } .unwrap() .0 }) .collect() } fn main() { let mut message_str = String::new(); io::stdin().read_to_string(&mut message_str).expect("Invalid input string!"); println!("The initial decoded message is: {}", deco...
{ let len = input.lines().map(|line| line.chars().count()).max().unwrap(); let mut histograms = vec![HashMap::new(); len]; for line in input.lines() { for (pos, ch) in line.chars().enumerate() { let cnt = histograms[pos].entry(ch).or_insert(0); *cnt += 1; } } ...
identifier_body
main.rs
#![feature(iter_max_by, iter_min_by)] use std::collections::HashMap; use std::io; use std::io::prelude::*; enum
{ MostLikely, LeastLikely, } fn decode_message(input: &str, method: DecodingMethod) -> String { let len = input.lines().map(|line| line.chars().count()).max().unwrap(); let mut histograms = vec![HashMap::new(); len]; for line in input.lines() { for (pos, ch) in line.chars().enumerate() {...
DecodingMethod
identifier_name
main.rs
#![feature(iter_max_by, iter_min_by)] use std::collections::HashMap; use std::io; use std::io::prelude::*; enum DecodingMethod { MostLikely, LeastLikely, } fn decode_message(input: &str, method: DecodingMethod) -> String { let len = input.lines().map(|line| line.chars().count()).max().unwrap(); let...
.map(|h| { match method { DecodingMethod::MostLikely => { h.into_iter().max_by(|&(_, cnt_a), &(_, cnt_b)| cnt_a.cmp(&cnt_b)) } DecodingMethod::LeastLikely => { h.into_iter().min_by(|&(_, cnt_a)...
*cnt += 1; } } histograms.into_iter()
random_line_split
vec-tail-matching.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 ...
match tail { [Foo {.. }, _, Foo {.. },.. _tail] => { unreachable!(); } [Foo { string: ref a }, Foo { string: ref b }] => { assert_eq!("bar", a.as_slice().slice(0, a.len())); assert_eq!("baz", b.as_sli...
random_line_split
vec-tail-matching.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 ...
() { let x = [ Foo { string: "foo".to_string() }, Foo { string: "bar".to_string() }, Foo { string: "baz".to_string() } ]; match x { [ref first,..tail] => { assert!(first.string == "foo".to_string()); assert_eq!(tail.len(), 2); assert!(tail[...
main
identifier_name
vec-tail-matching.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 ...
[Foo { string: ref a }, Foo { string: ref b }] => { assert_eq!("bar", a.as_slice().slice(0, a.len())); assert_eq!("baz", b.as_slice().slice(0, b.len())); } _ => { unreachable!(); } } ...
{ unreachable!(); }
conditional_block
vec-tail-matching.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 ...
} _ => { unreachable!(); } } } } }
{ let x = [ Foo { string: "foo".to_string() }, Foo { string: "bar".to_string() }, Foo { string: "baz".to_string() } ]; match x { [ref first, ..tail] => { assert!(first.string == "foo".to_string()); assert_eq!(tail.len(), 2); assert!(tail[0]...
identifier_body
package_id.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 ...
path: Path, /// Short name. This is the path's filestem, but we store it /// redundantly so as to not call get() everywhere (filestem() returns an /// option) /// The short name does not need to be a valid Rust identifier. /// Users can write: `extern mod foo = "...";` to get around the issue ...
/// the sources into a local directory in the RUST_PATH).
random_line_split
package_id.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 ...
} impl PkgId { pub fn new(s: &str) -> PkgId { use conditions::bad_pkg_id::cond; let mut given_version = None; // Did the user request a specific version? let s = match split_version(s) { Some((path, v)) => { given_version = Some(v); pat...
{ self.path == other.path && self.version == other.version }
identifier_body
package_id.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 ...
let short_name = path.filestem().expect(fmt!("Strange path! %s", s)); let version = match given_version { Some(v) => v, None => match try_getting_local_version(&path) { Some(v) => v, None => match try_getting_version(&path) { ...
{ return cond.raise((path, ~"0-length pkgid")); }
conditional_block
package_id.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 ...
(&self) -> ~str { fmt!("install(%s)", self.to_str()) } } struct Prefixes { priv components: ~[~str], priv remaining: ~[~str] } impl Iterator<(Path, Path)> for Prefixes { #[inline] fn next(&mut self) -> Option<(Path, Path)> { if self.components.len() <= 1 { None ...
install_tag
identifier_name
leafmt.rs
//! Lea code formatter. // FIXME This requires the parser to preserve comments to work properly // This is blocked on an upstream issue: https://github.com/kevinmehall/rust-peg/issues/84 #[macro_use] extern crate clap; extern crate term; extern crate rustc_serialize; extern crate lea_parser as parser; extern crate le...
() -> Box<term::StderrTerminal> { term::stderr().unwrap_or_else(|| Box::new(DummyTerm(io::stderr()))) } /// Parses the given source code and pretty-prints it fn prettyprint<W: Write>(code: &str, source_name: &str, mut target: W) -> io::Result<()> { match parser::block(code) { Ok(main) => { ...
stderr_term
identifier_name