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
util.rs
// // imag - the personal information management suite for the commandline // Copyright (C) 2015-2020 Matthias Beyer <mail@beyermatthias.de> and contributors // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the F...
{ use toml_query::read::TomlValueReadExt; let setting_name = "ref.basepathes"; rt.config() .ok_or_else(|| anyhow!("No configuration, cannot find collection name for {}", app_name))? .read_deserialized::<RefConfig>(setting_name)? .ok_or_else(|| anyhow!("Setting missing: {}", setting...
identifier_body
struct-destructuring-cross-crate.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...
{ let x = struct_destructuring_cross_crate::S { x: 1, y: 2 }; let struct_destructuring_cross_crate::S { x: a, y: b } = x; assert_eq!(a, 1); assert_eq!(b, 2); }
identifier_body
struct-destructuring-cross-crate.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...
() { let x = struct_destructuring_cross_crate::S { x: 1, y: 2 }; let struct_destructuring_cross_crate::S { x: a, y: b } = x; assert_eq!(a, 1); assert_eq!(b, 2); }
main
identifier_name
struct-destructuring-cross-crate.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.
// 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. // aux-build:struct_destructuring_cross_crate.rs extern crate struct_destructuring_cro...
// // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
random_line_split
issue-14919.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 ...
(&mut self) -> Option<(usize, usize)> { self.matcher.next_match() } } fn match_indices<'a, M, T: IntoMatcher<'a, M>>(s: &'a str, from: T) -> MatchIndices<M> { let string_matcher = from.into_matcher(s); MatchIndices { matcher: string_matcher } } fn main() { let s = "abcbdef"; match_indices(...
next
identifier_name
issue-14919.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 ...
trait Matcher { fn next_match(&mut self) -> Option<(usize, usize)>; } struct CharPredMatcher<'a, 'b> { str: &'a str, pred: Box<FnMut(char) -> bool + 'b>, } impl<'a, 'b> Matcher for CharPredMatcher<'a, 'b> { fn next_match(&mut self) -> Option<(usize, usize)> { None } } trait IntoMatcher<'...
// pretty-expanded FIXME #23616
random_line_split
issue-14919.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 ...
fn main() { let s = "abcbdef"; match_indices(s, |c: char| c == 'b') .collect::<Vec<(usize, usize)>>(); }
{ let string_matcher = from.into_matcher(s); MatchIndices { matcher: string_matcher } }
identifier_body
triple_loop.rs
pub use matrix::{Scalar,Mat}; pub use composables::{GemmNode,AlgorithmStep}; pub use thread_comm::ThreadInfo; pub struct TripleLoop{} impl<T: Scalar, At: Mat<T>, Bt: Mat<T>, Ct: Mat<T>> GemmNode<T, At, Bt, Ct> for TripleLoop { unsafe fn run(&mut self, a: &mut At, b: &mut Bt, c: &mut Ct, _thr: &ThreadInfo<T>) ...
() -> Self { TripleLoop{} } fn hierarchy_description() -> Vec<AlgorithmStep> { Vec::new() } }
new
identifier_name
triple_loop.rs
pub use matrix::{Scalar,Mat}; pub use composables::{GemmNode,AlgorithmStep}; pub use thread_comm::ThreadInfo; pub struct TripleLoop{} impl<T: Scalar, At: Mat<T>, Bt: Mat<T>, Ct: Mat<T>> GemmNode<T, At, Bt, Ct> for TripleLoop { unsafe fn run(&mut self, a: &mut At, b: &mut Bt, c: &mut Ct, _thr: &ThreadInfo<T>) ...
fn new() -> Self { TripleLoop{} } fn hierarchy_description() -> Vec<AlgorithmStep> { Vec::new() } }
c.set(y, x, t); } } } }
random_line_split
triple_loop.rs
pub use matrix::{Scalar,Mat}; pub use composables::{GemmNode,AlgorithmStep}; pub use thread_comm::ThreadInfo; pub struct TripleLoop{} impl<T: Scalar, At: Mat<T>, Bt: Mat<T>, Ct: Mat<T>> GemmNode<T, At, Bt, Ct> for TripleLoop { unsafe fn run(&mut self, a: &mut At, b: &mut Bt, c: &mut Ct, _thr: &ThreadInfo<T>) ...
fn hierarchy_description() -> Vec<AlgorithmStep> { Vec::new() } }
{ TripleLoop{} }
identifier_body
parser_testing.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 ...
/// Parse a string, return a pat. Uses "irrefutable"... which doesn't /// (currently) affect parsing. pub fn string_to_pat(source_str: String) -> P<ast::Pat> { let ps = ParseSess::new(FilePathMapping::empty()); with_error_checking_parse(source_str, &ps, |p| { p.parse_pat(None) }) } /// Convert a ...
{ let ps = ParseSess::new(FilePathMapping::empty()); with_error_checking_parse(source_str, &ps, |p| { p.parse_item() }) }
identifier_body
parser_testing.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 ...
() { assert_eq!(matches_codepattern("",""),true); assert_eq!(matches_codepattern("","a"),false); assert_eq!(matches_codepattern("a",""),false); assert_eq!(matches_codepattern("a","a"),true); assert_eq!(matches_codepattern("a b","a \n\t\r b"),true); assert_eq!(matches_c...
eqmodws
identifier_name
parser_testing.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 ...
return false } } // check if a has *only* trailing whitespace a_iter.all(is_pattern_whitespace) } /// Advances the given peekable `Iterator` until it reaches a non-whitespace character fn scan_for_non_ws_or_end<I: Iterator<Item= char>>(iter: &mut Peekable<I>) { while lexer::is_patt...
b_iter.next(); } else {
random_line_split
xul.mako.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ <%namespace name="helpers" file="/helpers.mako.rs" /> <% from data import Method %> // Non-standard properties t...
alias="-webkit-box-direction", spec="Nonstandard (https://developer.mozilla.org/en-US/docs/Web/CSS/box-direction)", )} ${helpers.predefined_type( "-moz-box-flex", "NonNegativeNumber", "From::from(0.)", products="gecko", gecko_ffi_name="mBoxFlex", animation_value_type="NonNegativeNumber"...
random_line_split
issue-3121.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 ...
meal::for_here(_) if cond => {} meal::for_here(order::hamburger) => {} meal::for_here(order::fries(_s)) => {} meal::for_here(order::shake) => {} } } pub fn main() { foo(box meal::for_here(order::hamburger), true) }
{ }
conditional_block
issue-3121.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
} pub fn main() { foo(box meal::for_here(order::hamburger), true) }
random_line_split
issue-3121.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 ...
{ hamburger, fries(side), shake } #[derive(Copy, Clone)] enum meal { to_go(order), for_here(order) } fn foo(m: Box<meal>, cond: bool) { match *m { meal::to_go(_) => { } meal::for_here(_) if cond => {} meal::for_here(order::hamburger) => {} meal::for_here(order::fries(_s)) => {} meal:...
order
identifier_name
skia.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/. #![allow(non_upper_case_globals)] #![allow(non_camel_case_types)] #![allow(non_snake_case)] use libc::*; pub type S...
pub fn SkiaSkNativeSharedGLContextGetFBOID(aGLContext: SkiaSkNativeSharedGLContextRef) -> c_uint; pub fn SkiaSkNativeSharedGLContextStealSurface(aGLContext: SkiaSkNativeSharedGLContextRef) -> SkiaGrGLSharedSurfaceRef; pub fn SkiaSkNativeSharedGLContextGetGrContext(aGLContext: SkiaSkNativeSharedGLContextRef) -> SkiaGrCo...
random_line_split
op.rs
nop_assign<'a,'tcx>(fcx: &FnCtxt<'a,'tcx>, expr: &'tcx ast::Expr, op: ast::BinOp, lhs_expr: &'tcx ast::Expr, rhs_expr: &'tcx ast::Expr) { let tcx = fcx.ccx.tcx; check_expr...
None => { Err(()) } } } // Binary operator categories. These categories summarize the behavior // with respect to the builtin operationrs supported. enum BinOpCategory { /// &&, || -- cannot be overridden Shortcircuit, /// <<, >> -- when shifting a single integer, rhs can ...
{ let method_ty = method.ty; // HACK(eddyb) Fully qualified path to work around a resolve bug. let method_call = ::middle::ty::MethodCall::expr(expr.id); fcx.inh.method_map.borrow_mut().insert(method_call, method); // extract return type for method; all late...
conditional_block
op.rs
_binop_assign<'a,'tcx>(fcx: &FnCtxt<'a,'tcx>, expr: &'tcx ast::Expr, op: ast::BinOp, lhs_expr: &'tcx ast::Expr, rhs_expr: &'tcx ast::Expr) { let tcx = fcx.ccx.tcx; check_e...
/// 1. Builtin operations can trivially be evaluated in constants. /// 2. For comparison operators applied to SIMD types the result is /// not of type `bool`. For example, `i16x4==i16x4` yields a /// type like `i16x4`. This means that the overloaded trait /// `PartialEq` is not applicable. /// /// Reason #2 is...
/// everything uniformly through the trait system and intrinsics or /// something like that): ///
random_line_split
op.rs
nop_assign<'a,'tcx>(fcx: &FnCtxt<'a,'tcx>, expr: &'tcx ast::Expr, op: ast::BinOp, lhs_expr: &'tcx ast::Expr, rhs_expr: &'tcx ast::Expr) { let tcx = fcx.ccx.tcx; check_expr...
<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>, expr: &'tcx ast::Expr, lhs_expr: &'tcx ast::Expr, lhs_ty: Ty<'tcx>, rhs_expr: &'tcx ast::Expr, op: ast::B...
check_overloaded_binop
identifier_name
lib.rs
//! A simple crate the wraps the turtl core shared lib and adds some handy dandy //! functions around it so we can call into it without having to wrap the C API //! each fing time. Great for integration tests or a websocket wrapper etc etc. use ::std::{env, thread, slice, str}; use ::std::ffi::CString; use ::std::time:...
let slice = unsafe { slice::from_raw_parts(msg_c, len) }; let res_str = str::from_utf8(slice).expect("cwrap::recv_event_nb() -- failed to parse utf8 str"); let ret = String::from(res_str); unsafe { turtlc_free(msg_c, len); } Some(ret) } pub fn lasterr() -> Option<String> { let ptr ...
{ return None; }
conditional_block
lib.rs
//! A simple crate the wraps the turtl core shared lib and adds some handy dandy //! functions around it so we can call into it without having to wrap the C API //! each fing time. Great for integration tests or a websocket wrapper etc etc. use ::std::{env, thread, slice, str}; use ::std::ffi::CString; use ::std::time:...
handle } /// Send a message to the core pub fn send(msg: &str) { let msg_vec = Vec::from(String::from(msg).as_bytes()); let ret = unsafe { turtlc_send(msg_vec.as_ptr(), msg_vec.len()) }; if ret!= 0 { panic!("Error sending msg: err {}", ret); } } /// Receive a message from the ...
{ if env::var("TURTL_CONFIG_FILE").is_err() { env::set_var("TURTL_CONFIG_FILE", "../config.yaml"); } let config_copy = String::from(app_config); let handle = thread::spawn(move || { // send in a the config options we need for our tests let app_config = config_copy.as_str(); ...
identifier_body
lib.rs
//! A simple crate the wraps the turtl core shared lib and adds some handy dandy //! functions around it so we can call into it without having to wrap the C API //! each fing time. Great for integration tests or a websocket wrapper etc etc. use ::std::{env, thread, slice, str}; use ::std::ffi::CString; use ::std::time:...
} } let slice = unsafe { slice::from_raw_parts(msg_c, len) }; let res_str = str::from_utf8(slice).expect("cwrap::recv_event() -- failed to parse utf8 str"); let ret = String::from(res_str); unsafe { turtlc_free(msg_c, len); } ret } /// Receive a core event (non blocking) pub...
None => panic!("recv_event() -- got empty msg and couldn't grab lasterr"),
random_line_split
lib.rs
//! A simple crate the wraps the turtl core shared lib and adds some handy dandy //! functions around it so we can call into it without having to wrap the C API //! each fing time. Great for integration tests or a websocket wrapper etc etc. use ::std::{env, thread, slice, str}; use ::std::ffi::CString; use ::std::time:...
(msg: &str) { let msg_vec = Vec::from(String::from(msg).as_bytes()); let ret = unsafe { turtlc_send(msg_vec.as_ptr(), msg_vec.len()) }; if ret!= 0 { panic!("Error sending msg: err {}", ret); } } /// Receive a message from the core, blocking (note that if you are not using /// {"reqr...
send
identifier_name
day1.rs
use std::collections::HashSet; #[derive(Hash, Eq, PartialEq, Debug, Clone)] enum Cardinal { West, North, East, South, } #[derive(Hash, Eq, PartialEq, Debug, Clone)] enum Turn { Left, Right, } #[derive(Hash, Eq, PartialEq, Debug, Clone)] struct Coord(i32, i32); #[derive(Hash, Eq, PartialEq, D...
} } } } fn main() { let directions = "L3, R2, L5, R1, L1, L2, L2, R1, R5, R1, L1, L2, R2, R4, L4, L3, L3, R5, L1, R3, L5, L2, \ R4, L5, R4, R2, L2, L1, R1, L3, L3, R2, R1, L4, L1, L1, R4, R5, R1, L2, L1, R188, R4, \ L3, R54, L4, R4, R74, R2, L4, R185, R1, R3, R5, L...
Cardinal::East => { self.east = self.east + length; } Cardinal::South => { self.south = self.south + length;
random_line_split
day1.rs
use std::collections::HashSet; #[derive(Hash, Eq, PartialEq, Debug, Clone)] enum Cardinal { West, North, East, South, } #[derive(Hash, Eq, PartialEq, Debug, Clone)] enum Turn { Left, Right, } #[derive(Hash, Eq, PartialEq, Debug, Clone)] struct Coord(i32, i32); #[derive(Hash, Eq, PartialEq, D...
{ current_direction: Cardinal, west: i32, north: i32, east: i32, south: i32, } impl Steps { fn add_steps_with_direction(&mut self, direction: &Cardinal, length: &i32) { match direction.clone() { Cardinal::West => { self.west = self.west + length; ...
Steps
identifier_name
day1.rs
use std::collections::HashSet; #[derive(Hash, Eq, PartialEq, Debug, Clone)] enum Cardinal { West, North, East, South, } #[derive(Hash, Eq, PartialEq, Debug, Clone)] enum Turn { Left, Right, } #[derive(Hash, Eq, PartialEq, Debug, Clone)] struct Coord(i32, i32); #[derive(Hash, Eq, PartialEq, D...
fn next_journey(direction: &Cardinal, length: &i32, journey: &mut Steps) { journey.current_direction = direction.clone(); journey.add_steps_with_direction(direction, length); } fn parse_turn_length(raw_direction: &str, current_direction: &Cardinal) -> (Cardinal, i32) { let ref turn = raw_direction[0..1];...
{ (journey.west - journey.east).abs() + (journey.north - journey.south).abs() }
identifier_body
multiwindow.rs
#![feature(phase)] #[cfg(target_os = "android")] #[phase(plugin, link)] extern crate android_glue; extern crate glutin; use std::thread::Thread; mod support; #[cfg(target_os = "android")] android_start!(main); #[cfg(not(feature = "window"))] fn main() { println!("This example requires glutin to be compiled with t...
() { let window1 = glutin::Window::new().unwrap(); let window2 = glutin::Window::new().unwrap(); let window3 = glutin::Window::new().unwrap(); let t1 = Thread::spawn(move || { run(window1, (0.0, 1.0, 0.0, 1.0)); }); let t2 = Thread::spawn(move || { run(window2, (0.0, 0.0, 1.0, ...
main
identifier_name
multiwindow.rs
#![feature(phase)] #[cfg(target_os = "android")]
#[phase(plugin, link)] extern crate android_glue; extern crate glutin; use std::thread::Thread; mod support; #[cfg(target_os = "android")] android_start!(main); #[cfg(not(feature = "window"))] fn main() { println!("This example requires glutin to be compiled with the `window` feature"); } #[cfg(feature = "window"...
random_line_split
multiwindow.rs
#![feature(phase)] #[cfg(target_os = "android")] #[phase(plugin, link)] extern crate android_glue; extern crate glutin; use std::thread::Thread; mod support; #[cfg(target_os = "android")] android_start!(main); #[cfg(not(feature = "window"))] fn main() { println!("This example requires glutin to be compiled with t...
{ unsafe { window.make_current() }; let context = support::load(&window); while !window.is_closed() { context.draw_frame(color); window.swap_buffers(); window.wait_events().collect::<Vec<glutin::Event>>(); } }
identifier_body
by-value-non-immediate-argument.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 ...
// check:$5 = {7, 8, 9.5, 10.5} // debugger:continue // debugger:finish // debugger:print a // check:$6 = {11.5, 12.5, 13, 14} // debugger:continue // debugger:finish // debugger:print x // check:$7 = {{Case1, x = 0, y = 8970181431921507452}, {Case1, 0, 2088533116, 2088533116}} // debugger:continue #[deriving(Clone)...
random_line_split
by-value-non-immediate-argument.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 ...
{ a: Struct, b: Struct } fn fun(s: Struct) { zzz(); } fn fun_fun(StructStruct { a: x, b: Struct { a: y, b: z } }: StructStruct) { zzz(); } fn tup(a: (int, uint, float, float)) { zzz(); } struct Newtype(float, float, int, uint); fn new_type(a: Newtype) { zzz(); } // The first element is to...
StructStruct
identifier_name
sink.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/. */ //! Small helpers to abstract over different containers. #![deny(missing_docs)] use smallvec::{Array, SmallVec}; ...
} impl<A: Array> Push<A::Item> for SmallVec<A> { fn push(&mut self, value: A::Item) { SmallVec::push(self, value); } }
{ Vec::push(self, value); }
identifier_body
sink.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/. */ //! Small helpers to abstract over different containers. #![deny(missing_docs)] use smallvec::{Array, SmallVec}; ...
SmallVec::push(self, value); } }
impl<A: Array> Push<A::Item> for SmallVec<A> { fn push(&mut self, value: A::Item) {
random_line_split
sink.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/. */ //! Small helpers to abstract over different containers. #![deny(missing_docs)] use smallvec::{Array, SmallVec}; ...
(&mut self, value: T) { Vec::push(self, value); } } impl<A: Array> Push<A::Item> for SmallVec<A> { fn push(&mut self, value: A::Item) { SmallVec::push(self, value); } }
push
identifier_name
hello.rs
#[no_mangle] pub extern fn hello() { // The statements here will be executed when the compiled binary is called // Print text to the console println!("Hello World!"); } // The Computer Language Benchmarks Game // http://benchmarksgame.alioth.debian.org/ // // contributed by the Rust Project Developers // ...
self.data.iter() .skip_while(|pc| pc.0 < r) .map(|&(_, c)| c) .next() } } fn make_fasta<W: Writer, I: Iterator<Item=u8>>( wr: &mut W, header: &str, mut it: I, mut n: usize) -> std::io::IoResult<()> { //try!(wr.write(header.as_bytes())); let mut line = [0u8; ...
type Item = u8; fn next(&mut self) -> Option<u8> { let r = self.rng.gen();
random_line_split
hello.rs
#[no_mangle] pub extern fn hello() { // The statements here will be executed when the compiled binary is called // Print text to the console println!("Hello World!"); } // The Computer Language Benchmarks Game // http://benchmarksgame.alioth.debian.org/ // // contributed by the Rust Project Developers // ...
<W: Writer, I: Iterator<Item=u8>>( wr: &mut W, header: &str, mut it: I, mut n: usize) -> std::io::IoResult<()> { //try!(wr.write(header.as_bytes())); let mut line = [0u8; LINE_LENGTH + 1]; while n > 0 { let nb = min(LINE_LENGTH, n); for i in (0..nb) { line[i] = it.next()....
make_fasta
identifier_name
hello.rs
#[no_mangle] pub extern fn hello() { // The statements here will be executed when the compiled binary is called // Print text to the console println!("Hello World!"); } // The Computer Language Benchmarks Game // http://benchmarksgame.alioth.debian.org/ // // contributed by the Rust Project Developers // ...
{ run(&mut io::stdout()).unwrap() }
identifier_body
lib.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #![deny(unsafe_code)] extern crate base64; extern crate brotli; extern crate cookie as cookie_rs; extern crate de...
extern crate immeta; extern crate ipc_channel; #[macro_use] extern crate lazy_static; #[macro_use] extern crate log; extern crate malloc_size_of; #[macro_use] extern crate malloc_size_of_derive; #[macro_use] #[no_link] extern crate matches; #[macro_use] extern crate mime; extern crate mime_guess; extern crate msg; exte...
extern crate hyper; extern crate hyper_openssl; extern crate hyper_serde;
random_line_split
future.rs
// Copyright 2018 TiKV Project Authors. Licensed under Apache-2.0. use crate::callback::must_call; use futures::channel::mpsc; use futures::channel::oneshot as futures_oneshot; use futures::future::{self, BoxFuture, Future, FutureExt, TryFutureExt}; use futures::stream::{Stream, StreamExt}; use futures::task::{self, A...
size: usize, ) -> ( impl Stream<Item = T> + Send +'static, impl Future<Output = ()> + Send +'static, ) where S: Stream<Item = T> + Send +'static, T: Send +'static, { let (tx, rx) = mpsc::channel::<T>(size); let driver = s .then(future::ok::<T, mpsc::SendError>) .forward(tx) ...
s: S,
random_line_split
future.rs
// Copyright 2018 TiKV Project Authors. Licensed under Apache-2.0. use crate::callback::must_call; use futures::channel::mpsc; use futures::channel::oneshot as futures_oneshot; use futures::future::{self, BoxFuture, Future, FutureExt, TryFutureExt}; use futures::stream::{Stream, StreamExt}; use futures::task::{self, A...
}); (callback, future) } pub fn paired_must_called_future_callback<T>( arg_on_drop: impl FnOnce() -> T + Send +'static, ) -> (Box<dyn FnOnce(T) + Send>, futures_oneshot::Receiver<T>) where T: Send +'static, { let (tx, future) = futures_oneshot::channel::<T>(); let callback = must_call( ...
{ warn!("paired_future_callback: Failed to send result to the future rx, discarded."); }
conditional_block
future.rs
// Copyright 2018 TiKV Project Authors. Licensed under Apache-2.0. use crate::callback::must_call; use futures::channel::mpsc; use futures::channel::oneshot as futures_oneshot; use futures::future::{self, BoxFuture, Future, FutureExt, TryFutureExt}; use futures::stream::{Stream, StreamExt}; use futures::task::{self, A...
<F: Future<Output = ()> + Send +'static>(f: F) { let f: BoxFuture<'static, ()> = Box::pin(f); let waker = Arc::new(BatchCommandsWaker(Mutex::new(Some(f)))); waker.wake(); } // BatchCommandsWaker is used to make business pool notifiy completion queues directly. struct BatchCommandsWaker(Mutex<Option<BoxFutu...
poll_future_notify
identifier_name
denominations.rs
// Copyright 2015, 2016 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any la...
() -> U256 { U256::exp10(15) } #[inline] /// 1 Szabo in Wei pub fn szabo() -> U256 { U256::exp10(12) } #[inline] /// 1 Shannon in Wei pub fn shannon() -> U256 { U256::exp10(9) } #[inline] /// 1 Wei in Wei pub fn wei() -> U256 { U256::exp10(0) }
finney
identifier_name
denominations.rs
// Copyright 2015, 2016 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any la...
/// 1 Wei in Wei pub fn wei() -> U256 { U256::exp10(0) }
random_line_split
denominations.rs
// Copyright 2015, 2016 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any la...
#[inline] /// 1 Wei in Wei pub fn wei() -> U256 { U256::exp10(0) }
{ U256::exp10(9) }
identifier_body
breakctr.rs
use std::env; use std::slice; use std::io::prelude::*; use common::{err, challenge, ascii, base64, util, charfreq}; use common::cipher::one_byte_xor as obx; use common::cipher::aes; use common::cipher::cipherbox as cb; pub static info: challenge::Info = challenge::Info { no: 19, title: "Break fi...
} let mut r2: Vec<(u8, usize)> = util::freq(&r); // get a count of occurrence of each of the keys r2.sort_by(|&a, &b| (b.1).cmp(&(a.1))); // sort by descending count // only take the first "n" candidate keys re...
random_line_split
breakctr.rs
use std::env; use std::slice; use std::io::prelude::*; use common::{err, challenge, ascii, base64, util, charfreq}; use common::cipher::one_byte_xor as obx; use common::cipher::aes; use common::cipher::cipherbox as cb; pub static info: challenge::Info = challenge::Info { no: 19, title: "Break fi...
(ciphers: &Vec<Vec<u8>>, guesses: &Vec<(usize, &str)>) -> Result<Vec<String>, err::Error> { let keystream = try!(break_ctr(&ciphers)); let plains = try!(manual_guess_for_last_chars(&ciphers, &keystream, &guesses)); Ok(plains) } // this function will keep asking the user for his guesses for last charac...
break_ctr_with_manual_guess_for_last_chars
identifier_name
breakctr.rs
use std::env; use std::slice; use std::io::prelude::*; use common::{err, challenge, ascii, base64, util, charfreq}; use common::cipher::one_byte_xor as obx; use common::cipher::aes; use common::cipher::cipherbox as cb; pub static info: challenge::Info = challenge::Info { no: 19, title: "Break fi...
for i in 0.. new_ks_bytes.len() { if suffix_r[i]!= '#' as u8 { new_keystream[ks_start + i] = new_ks_bytes[i]; } } Ok(new_keystream) }; if guesses.len() > 0 { // guesses provided, so, don't ask the user for guess in guesses { ...
{ let mut plains = xor_keystream(&ciphers, &auto_guess_keystream); let mut keystream = auto_guess_keystream.clone(); fn display(plains: &Vec<String>) { // display plain text lines with line numbers let mut c = 0; for p in plains { println!("{:02} {}", c, p); c ...
identifier_body
breakctr.rs
use std::env; use std::slice; use std::io::prelude::*; use common::{err, challenge, ascii, base64, util, charfreq}; use common::cipher::one_byte_xor as obx; use common::cipher::aes; use common::cipher::cipherbox as cb; pub static info: challenge::Info = challenge::Info { no: 19, title: "Break fi...
} Ok(keystream) } fn filter_candidates(col: usize, c: &Vec<u8>) -> Result<(Vec<u8>, Vec<u32>), err::Error> { let tri_col: Vec<u8> = trigrams_col_no_weights!(col, trigrams_limit, ""); let result: Vec<u8>; let weights: Vec<u32> = Vec::<u32>::new(); // will not contain weights //println!("...
{ all_ciphers_done = true; }
conditional_block
space_map_disk.rs
use anyhow::Result; use crate::pdata::btree_builder::*; use crate::pdata::space_map::*; use crate::pdata::space_map_common::*; use crate::write_batcher::*; //------------------------------------------ pub fn write_disk_sm(w: &mut WriteBatcher, sm: &dyn SpaceMap) -> Result<SMRoot> { let (index_entries, ref_count_...
w.flush()?; Ok(SMRoot { nr_blocks: sm.get_nr_blocks()?, nr_allocated: sm.get_nr_allocated()?, bitmap_root, ref_count_root, }) } //------------------------------------------
let bitmap_root = index_builder.complete(w)?;
random_line_split
structure.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...
} } } } } #[macro_export] macro_rules! gfx_vertex_struct { ($root:ident { $( $field:ident: $ty:ty = $name:expr, )* }) => (gfx_impl_struct!{ $crate::format::Format : $crate::format::Formatted = $root { $( $field: $ty = $name, )* ...
stride: stride, }), )* _ => None,
random_line_split
owned_stack.rs
// This file is part of libfringe, a low-level green threading library. // Copyright (c) whitequark <whitequark@whitequark.org> // See the LICENSE file included in this distribution. extern crate alloc; use core::slice; use self::alloc::heap; use self::alloc::boxed::Box; /// OwnedStack holds a non-guarded, heap-alloc...
(size: usize) -> OwnedStack { unsafe { let ptr = heap::allocate(size, ::STACK_ALIGNMENT); OwnedStack(Box::from_raw(slice::from_raw_parts_mut(ptr, size))) } } } impl ::stack::Stack for OwnedStack { #[inline(always)] fn base(&self) -> *mut u8 { // The slice can...
new
identifier_name
owned_stack.rs
// This file is part of libfringe, a low-level green threading library. // Copyright (c) whitequark <whitequark@whitequark.org> // See the LICENSE file included in this distribution. extern crate alloc; use core::slice; use self::alloc::heap; use self::alloc::boxed::Box; /// OwnedStack holds a non-guarded, heap-alloc...
pub fn new(size: usize) -> OwnedStack { unsafe { let ptr = heap::allocate(size, ::STACK_ALIGNMENT); OwnedStack(Box::from_raw(slice::from_raw_parts_mut(ptr, size))) } } } impl ::stack::Stack for OwnedStack { #[inline(always)] fn base(&self) -> *mut u8 { //...
impl OwnedStack { /// Allocates a new stack with exactly `size` accessible bytes and alignment appropriate /// for the current platform using the default Rust allocator.
random_line_split
crypto.rs
use argon2::{self, Config, ThreadMode, Variant, Version}; use errors::Error; // hash encodes plaintext with a salt vector slice. Returns encoded string or // fails with [argon2::Error](https://docs.rs/rust-argon2/0.3.0/argon2/enum.Error.html) pub fn hash(password: &str, salt: Vec<u8>) -> Result<String, Error> { /...
// For optimal security, cost parameters should be fine tuned to machine // CPU and memory specs. // // ref: https://github.com/P-H-C/phc-winner-argon2/blob/master/argon2-specs.pdf let cfg = Config { variant: Variant::Argon2id, version: Version::Version13, mem_cost: 512, ...
random_line_split
crypto.rs
use argon2::{self, Config, ThreadMode, Variant, Version}; use errors::Error; // hash encodes plaintext with a salt vector slice. Returns encoded string or // fails with [argon2::Error](https://docs.rs/rust-argon2/0.3.0/argon2/enum.Error.html) pub fn hash(password: &str, salt: Vec<u8>) -> Result<String, Error> { /...
// generate_salt creates salt vector of a usize parameter. pub fn generate_salt(size: usize) -> Vec<u8> { nonce(size).as_bytes().to_vec() } // nonce takes a usize parameter for length fn nonce(take: usize) -> String { use rand::{self, Rng}; rand::thread_rng() .gen_ascii_chars() .take(take)...
{ let is_valid = argon2::verify_encoded(encoded_hash, password)?; Ok(is_valid) }
identifier_body
crypto.rs
use argon2::{self, Config, ThreadMode, Variant, Version}; use errors::Error; // hash encodes plaintext with a salt vector slice. Returns encoded string or // fails with [argon2::Error](https://docs.rs/rust-argon2/0.3.0/argon2/enum.Error.html) pub fn hash(password: &str, salt: Vec<u8>) -> Result<String, Error> { /...
() { let salt = generate_salt(24); assert_eq!(24, salt.len()); } #[test] fn hash_and_validate() { let salt = generate_salt(16); let digest = hash(&PWD, salt).unwrap(); let verified = verify(&digest, &PWD.as_bytes()).unwrap(); let should_eq_false = verify(&dig...
gen_salt
identifier_name
into_matcher.rs
use super::Matcher; use regex::{Regex, Captures}; impl From<Regex> for Matcher { fn from(regex: Regex) -> Matcher { let path = regex.as_str().to_string(); Matcher::new(path, regex) } } impl<'a> From<&'a str> for Matcher { fn from(s: &'a str) -> Matcher { From::from(s.to_string()) ...
// There should only ever be one match (after subgroup 0) let c = captures.iter().skip(1).next().unwrap(); format!("(?P<{}>[,a-zA-Z0-9%_-]*)", c.unwrap()) }); let line_regex = format!("^{}{}$", named_captures, REGEX_PARAM_SEQ); let regex = Regex::new(&line_re...
{ let with_format = if s.contains(FORMAT_VAR) { s } else { format!("{}(\\.{})?", s, FORMAT_VAR) }; // First mark all double wildcards for replacement. We can't directly // replace them since the replacement does contain the * symbol as well, // wh...
identifier_body
into_matcher.rs
use super::Matcher; use regex::{Regex, Captures}; impl From<Regex> for Matcher { fn from(regex: Regex) -> Matcher { let path = regex.as_str().to_string(); Matcher::new(path, regex) } } impl<'a> From<&'a str> for Matcher { fn
(s: &'a str) -> Matcher { From::from(s.to_string()) } } lazy_static! { static ref REGEX_VAR_SEQ: Regex = Regex::new(r":([,a-zA-Z0-9_-]*)").unwrap(); } pub static FORMAT_PARAM: &'static str = "format"; // FIXME: Once const fn lands this could be defined in terms of the above static FORMAT_VAR: ...
from
identifier_name
into_matcher.rs
use super::Matcher; use regex::{Regex, Captures}; impl From<Regex> for Matcher { fn from(regex: Regex) -> Matcher { let path = regex.as_str().to_string(); Matcher::new(path, regex) } } impl<'a> From<&'a str> for Matcher { fn from(s: &'a str) -> Matcher { From::from(s.to_string()) ...
else { format!("{}(\\.{})?", s, FORMAT_VAR) }; // First mark all double wildcards for replacement. We can't directly // replace them since the replacement does contain the * symbol as well, // which would get overwritten with the next replace call let with_placehold...
{ s }
conditional_block
into_matcher.rs
use super::Matcher; use regex::{Regex, Captures}; impl From<Regex> for Matcher { fn from(regex: Regex) -> Matcher { let path = regex.as_str().to_string(); Matcher::new(path, regex) } } impl<'a> From<&'a str> for Matcher { fn from(s: &'a str) -> Matcher { From::from(s.to_string()) ...
static FORMAT_VAR: &'static str = ":format"; static VAR_SEQ: &'static str = "[,a-zA-Z0-9_-]*"; static VAR_SEQ_WITH_SLASH: &'static str = "[,/a-zA-Z0-9_-]*"; // matches request params (e.g.?foo=true&bar=false) static REGEX_PARAM_SEQ: &'static str = "(\\?[a-zA-Z0-9%_=&-]*)?"; impl From<...
static ref REGEX_VAR_SEQ: Regex = Regex::new(r":([,a-zA-Z0-9_-]*)").unwrap(); } pub static FORMAT_PARAM: &'static str = "format"; // FIXME: Once const fn lands this could be defined in terms of the above
random_line_split
mod.rs
use crate::fx::FxHashMap; use crate::undo_log::{Rollback, Snapshots, UndoLogs, VecLog}; use std::borrow::{Borrow, BorrowMut}; use std::hash::Hash; use std::marker::PhantomData; use std::ops; pub use crate::undo_log::Snapshot; #[cfg(test)] mod tests; pub type SnapshotMapStorage<K, V> = SnapshotMap<K, V, FxHashMap<K, ...
pub fn get(&self, key: &K) -> Option<&V> { self.map.borrow().get(key) } } impl<K, V> SnapshotMap<K, V> where K: Hash + Clone + Eq, { pub fn snapshot(&mut self) -> Snapshot { self.undo_log.start_snapshot() } pub fn commit(&mut self, snapshot: Snapshot) { self.undo_log.co...
}
random_line_split
mod.rs
use crate::fx::FxHashMap; use crate::undo_log::{Rollback, Snapshots, UndoLogs, VecLog}; use std::borrow::{Borrow, BorrowMut}; use std::hash::Hash; use std::marker::PhantomData; use std::ops; pub use crate::undo_log::Snapshot; #[cfg(test)] mod tests; pub type SnapshotMapStorage<K, V> = SnapshotMap<K, V, FxHashMap<K, ...
UndoLog::Purged => {} } } }
{ self.insert(key, old_value); }
conditional_block
mod.rs
use crate::fx::FxHashMap; use crate::undo_log::{Rollback, Snapshots, UndoLogs, VecLog}; use std::borrow::{Borrow, BorrowMut}; use std::hash::Hash; use std::marker::PhantomData; use std::ops; pub use crate::undo_log::Snapshot; #[cfg(test)] mod tests; pub type SnapshotMapStorage<K, V> = SnapshotMap<K, V, FxHashMap<K, ...
pub fn remove(&mut self, key: K) -> bool { match self.map.borrow_mut().remove(&key) { Some(old_value) => { self.undo_log.push(UndoLog::Overwrite(key, old_value)); true } None => false, } } pub fn get(&self, key: &K) -> Op...
{ match self.map.borrow_mut().insert(key.clone(), value) { None => { self.undo_log.push(UndoLog::Inserted(key)); true } Some(old_value) => { self.undo_log.push(UndoLog::Overwrite(key, old_value)); false ...
identifier_body
mod.rs
use crate::fx::FxHashMap; use crate::undo_log::{Rollback, Snapshots, UndoLogs, VecLog}; use std::borrow::{Borrow, BorrowMut}; use std::hash::Hash; use std::marker::PhantomData; use std::ops; pub use crate::undo_log::Snapshot; #[cfg(test)] mod tests; pub type SnapshotMapStorage<K, V> = SnapshotMap<K, V, FxHashMap<K, ...
<L2>(&mut self, undo_log: L2) -> SnapshotMap<K, V, &mut M, L2> { SnapshotMap { map: &mut self.map, undo_log, _marker: PhantomData } } } impl<K, V, M, L> SnapshotMap<K, V, M, L> where K: Hash + Clone + Eq, M: BorrowMut<FxHashMap<K, V>> + Borrow<FxHashMap<K, V>>, L: UndoLogs<UndoLog<K, V>>, { ...
with_log
identifier_name
menu.rs
// Copyright 2013-2014 Jeffery Olson // // Licensed under the 3-Clause BSD License, see LICENSE.txt // at the top-level of this repository. // This file may not be copied, modified, or distributed // except according to those terms. use std::vec::Vec; use gfx::GameDisplay; use super::{UiBox, UiFont, draw_text_box, c...
formatted_entries: Vec::new(), bg_color: (0,0,0), selected_prefix: "".to_string(), unselected_prefix: "".to_string(), curr_selected: 0, coords: (0,0), box_size: (0,0), text_gap: 2 } } pub fn move_down(&mut se...
VertTextMenu { entries: Vec::new(),
random_line_split
menu.rs
// Copyright 2013-2014 Jeffery Olson // // Licensed under the 3-Clause BSD License, see LICENSE.txt // at the top-level of this repository. // This file may not be copied, modified, or distributed // except according to those terms. use std::vec::Vec; use gfx::GameDisplay; use super::{UiBox, UiFont, draw_text_box, c...
(&mut self, coords: (int, int), ui_font: &TFont, ui_box: &TBox) { // figure out width, in pixels, of the text (based on longest entry line) self.formatted_entries = Vec::new(); for v in range(0, self.entries.len()) { let formatted = self.get_formatted(v); self.formatted_e...
update_bounds
identifier_name
menu.rs
// Copyright 2013-2014 Jeffery Olson // // Licensed under the 3-Clause BSD License, see LICENSE.txt // at the top-level of this repository. // This file may not be copied, modified, or distributed // except according to those terms. use std::vec::Vec; use gfx::GameDisplay; use super::{UiBox, UiFont, draw_text_box, c...
else { &self.unselected_prefix }; format!("{} {}", *prefix, entry) } pub fn update_bounds(&mut self, coords: (int, int), ui_font: &TFont, ui_box: &TBox) { // figure out width, in pixels, of the text (based on longest entry line) self.formatted_entries = Vec::new(); ...
{ &self.selected_prefix }
conditional_block
main.rs
#![crate_name = "weather_client"] /*! * Weather update client * Connects SUB socket to tcp://localhost:5556 * Collects weather updates and find avg temp in zipcode */ extern crate zmq; use std::env; fn
(s: &str) -> i64 { s.parse().unwrap() } fn main() { println!("Collecting updates from weather server..."); let context = zmq::Context::new(); let subscriber = context.socket(zmq::SUB).unwrap(); assert!(subscriber.connect("tcp://localhost:5556").is_ok()); let args: Vec<String> = env::args().co...
atoi
identifier_name
main.rs
#![crate_name = "weather_client"] /*! * Weather update client * Connects SUB socket to tcp://localhost:5556 * Collects weather updates and find avg temp in zipcode */ extern crate zmq; use std::env; fn atoi(s: &str) -> i64
fn main() { println!("Collecting updates from weather server..."); let context = zmq::Context::new(); let subscriber = context.socket(zmq::SUB).unwrap(); assert!(subscriber.connect("tcp://localhost:5556").is_ok()); let args: Vec<String> = env::args().collect(); let filter = if args.len() > 1...
{ s.parse().unwrap() }
identifier_body
main.rs
#![crate_name = "weather_client"] /*! * Weather update client * Connects SUB socket to tcp://localhost:5556 * Collects weather updates and find avg temp in zipcode */ extern crate zmq; use std::env; fn atoi(s: &str) -> i64 { s.parse().unwrap() } fn main() { println!("Collecting updates from weather ser...
let string = subscriber.recv_string(0).unwrap().unwrap(); let chks: Vec<i64> = string.split(' ').map(atoi).collect(); let (_zipcode, temperature, _relhumidity) = (chks[0], chks[1], chks[2]); total_temp += temperature; } println!("Average temperature for zipcode '{}' was {}F", fi...
for _ in 0 .. 100 {
random_line_split
main.rs
#![crate_name = "weather_client"] /*! * Weather update client * Connects SUB socket to tcp://localhost:5556 * Collects weather updates and find avg temp in zipcode */ extern crate zmq; use std::env; fn atoi(s: &str) -> i64 { s.parse().unwrap() } fn main() { println!("Collecting updates from weather ser...
; assert!(subscriber.set_subscribe(filter.as_bytes()).is_ok()); let mut total_temp = 0; for _ in 0.. 100 { let string = subscriber.recv_string(0).unwrap().unwrap(); let chks: Vec<i64> = string.split(' ').map(atoi).collect(); let (_zipcode, temperature, _relhumidity) = (chks[0], chk...
{ "10001" }
conditional_block
ttf.rs
//! Module for creating text textures. use std::ffi::CString; use std::path::Path; use sdl2_sys::pixels::{SDL_Color,SDL_PIXELFORMAT_ARGB8888}; use sdl2_sys::surface::SDL_Surface; use sdl2_sys::surface; use gl; use common::color::Color4; use yaglw::gl_context::GLContext; use yaglw::texture::Texture2D; #[allow(non_ca...
impl Font { #[allow(missing_docs)] pub fn new(font: &Path, point_size: u32) -> Font { ensure_init(); let c_path = CString::new(font.to_str().unwrap().as_bytes()).unwrap(); let ptr = c_path.as_ptr() as *const i8; let p = unsafe { ffi::TTF_OpenFont(ptr, point_size as ffi::c_int) }; assert!(!p....
{ unsafe { if ffi::TTF_WasInit() == 0 { assert_eq!(ffi::TTF_Init(), 0); } } }
identifier_body
ttf.rs
//! Module for creating text textures. use std::ffi::CString; use std::path::Path; use sdl2_sys::pixels::{SDL_Color,SDL_PIXELFORMAT_ARGB8888}; use sdl2_sys::surface::SDL_Surface; use sdl2_sys::surface; use gl; use common::color::Color4; use yaglw::gl_context::GLContext; use yaglw::texture::Texture2D; #[allow(non_ca...
<'a>(&self, gl: &'a GLContext, txt: &str) -> Texture2D<'a> { self.render(gl, txt, Color4::of_rgba(0x55, 0x55, 0x55, 0xFF)) } } impl Drop for Font { fn drop(&mut self) { unsafe { ffi::TTF_CloseFont(self.p) } } } //#[test] //fn load_and_unload() { // Font::new(&Path::new("fonts/Open_Sans/OpenSans-Regular...
light
identifier_name
ttf.rs
//! Module for creating text textures. use std::ffi::CString; use std::path::Path; use sdl2_sys::pixels::{SDL_Color,SDL_PIXELFORMAT_ARGB8888}; use sdl2_sys::surface::SDL_Surface; use sdl2_sys::surface; use gl; use common::color::Color4; use yaglw::gl_context::GLContext; use yaglw::texture::Texture2D; #[allow(non_ca...
ffi::TTF_RenderUTF8_Blended(self.p as *const ffi::c_void, ptr, sdl_color) } }; let tex = unsafe { surface_ptr.as_ref().expect("Cannot render text.") }; unsafe { assert_eq!((*tex.format).format, SDL_PIXELFORMAT_ARGB8888); } let texture = Texture2D::new(gl); unsafe...
let surface_ptr = { let c_str = CString::new(txt.as_bytes()).unwrap(); let ptr = c_str.as_ptr() as *const i8; unsafe {
random_line_split
ttf.rs
//! Module for creating text textures. use std::ffi::CString; use std::path::Path; use sdl2_sys::pixels::{SDL_Color,SDL_PIXELFORMAT_ARGB8888}; use sdl2_sys::surface::SDL_Surface; use sdl2_sys::surface; use gl; use common::color::Color4; use yaglw::gl_context::GLContext; use yaglw::texture::Texture2D; #[allow(non_ca...
} } impl Font { #[allow(missing_docs)] pub fn new(font: &Path, point_size: u32) -> Font { ensure_init(); let c_path = CString::new(font.to_str().unwrap().as_bytes()).unwrap(); let ptr = c_path.as_ptr() as *const i8; let p = unsafe { ffi::TTF_OpenFont(ptr, point_size as ffi::c_int) }; asser...
{ assert_eq!(ffi::TTF_Init(), 0); }
conditional_block
websocket.rs
}; use dom::bindings::codegen::UnionTypes::StringOrStringSequence; use dom::bindings::conversions::ToJSValConvertible; use dom::bindings::error::{Error, ErrorResult, Fallible}; use dom::bindings::inheritance::Castable; use dom::bindings::refcounted::Trusted; use dom::bindings::reflector::{DomObject, reflect_dom_object}...
} struct BufferedAmountTask { address: Trusted<WebSocket>, } impl TaskOnce for BufferedAmountTask { // See https://html.spec.whatwg.org/multipage/#dom-websocket-bufferedamount // // To be compliant with standards, we need to reset bufferedAmount only when the event loop // reaches step 1. In our...
{ let ws = self.address.root(); // Step 1. ws.ready_state.set(WebSocketRequestState::Open); // Step 2: Extensions. // TODO: Set extensions to extensions in use. // Step 3. if let Some(protocol_name) = self.protocol_in_use { *ws.protocol.borrow_mut()...
identifier_body
websocket.rs
}; use dom::bindings::codegen::UnionTypes::StringOrStringSequence; use dom::bindings::conversions::ToJSValConvertible; use dom::bindings::error::{Error, ErrorResult, Fallible}; use dom::bindings::inheritance::Castable; use dom::bindings::refcounted::Trusted; use dom::bindings::reflector::{DomObject, reflect_dom_object}...
(&self, data_byte_len: u64) -> Fallible<bool> { let return_after_buffer = match self.ready_state.get() { WebSocketRequestState::Connecting => { return Err(Error::InvalidState); }, WebSocketRequestState::Open => false, WebSocketRequestState::Closing...
send_impl
identifier_name
websocket.rs
Methods}; use dom::bindings::codegen::UnionTypes::StringOrStringSequence; use dom::bindings::conversions::ToJSValConvertible; use dom::bindings::error::{Error, ErrorResult, Fallible}; use dom::bindings::inheritance::Castable; use dom::bindings::refcounted::Trusted; use dom::bindings::reflector::{DomObject, reflect_dom_...
fn Send_(&self, blob: &Blob) -> ErrorResult { /* As per https://html.spec.whatwg.org/multipage/#websocket the buffered amount needs to be clamped to u32, even though Blob.Size() is u64 If the buffer limit is reached in the first place, there are likely other major problems */ ...
// https://html.spec.whatwg.org/multipage/#dom-websocket-send
random_line_split
websocket.rs
}; use dom::bindings::codegen::UnionTypes::StringOrStringSequence; use dom::bindings::conversions::ToJSValConvertible; use dom::bindings::error::{Error, ErrorResult, Fallible}; use dom::bindings::inheritance::Castable; use dom::bindings::refcounted::Trusted; use dom::bindings::reflector::{DomObject, reflect_dom_object}...
// Step 2-5. let global = ws.global(); // global.get_cx() returns a valid `JSContext` pointer, so this is safe. unsafe { let cx = global.get_cx(); let _ac = JSAutoCompartment::new(cx, ws.reflector().get_jsobject().get()); rooted!(in(cx) let mut messa...
{ return; }
conditional_block
mod.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use common::FileKey; use fixture_tests::Fixture; use graphql_ir::{build, Program}; use graphql_syntax::parse; use graphql_text_prin...
.map(|def| print_fragment(&TEST_SCHEMA, def)) .collect::<Vec<_>>(); printed.sort(); Ok(printed.join("\n\n")) }
program.fragments().count() ); let mut printed = next_program .fragments()
random_line_split
mod.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use common::FileKey; use fixture_tests::Fixture; use graphql_ir::{build, Program}; use graphql_syntax::parse; use graphql_text_prin...
{ let file_key = FileKey::new(fixture.file_name); let ast = parse(fixture.content, file_key).unwrap(); let ir = build(&TEST_SCHEMA, &ast.definitions).unwrap(); let program = Program::from_definitions(&TEST_SCHEMA, ir); let next_program = sort_selections(&program); assert_eq!( next_progr...
identifier_body
mod.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use common::FileKey; use fixture_tests::Fixture; use graphql_ir::{build, Program}; use graphql_syntax::parse; use graphql_text_prin...
(fixture: &Fixture) -> Result<String, String> { let file_key = FileKey::new(fixture.file_name); let ast = parse(fixture.content, file_key).unwrap(); let ir = build(&TEST_SCHEMA, &ast.definitions).unwrap(); let program = Program::from_definitions(&TEST_SCHEMA, ir); let next_program = sort_selections(...
transform_fixture
identifier_name
11.rs
// SPDX-License-Identifier: MIT use clap::{Arg, App}; static DIRECTIONS : [(i64,i64); 8] = [ (-1,-1), ( 0,-1), ( 1,-1), (-1, 0), ( 1, 0), (-1, 1), ( 0, 1), ( 1, 1), ]; #[derive(Clone)] pub struct Floorplan { pub map: Vec<Vec<char>>, } impl Floorplan { pub fn
() -> Floorplan { Floorplan { map: Vec::new() } } pub fn load(fname: &str) -> Floorplan { let mut plan = Floorplan::new(); let contents = std::fs::read_to_string(fname) .unwrap_or_else(|err| panic!("Error reading {}: {}", fname, err)); for line in contents.trim_end_m...
new
identifier_name
11.rs
// SPDX-License-Identifier: MIT use clap::{Arg, App}; static DIRECTIONS : [(i64,i64); 8] = [ (-1,-1), ( 0,-1), ( 1,-1), (-1, 0), ( 1, 0), (-1, 1), ( 0, 1), ( 1, 1), ]; #[derive(Clone)] pub struct Floorplan { pub map: Vec<Vec<char>>, } impl Floorplan { pub fn new() -> Floorplan { ...
for (dx, dy) in DIRECTIONS.iter() { let (mut x, mut y) = (x as i64+dx, y as i64+dy); while x >= 0 && y >= 0 && x < xmax && y < ymax { match self.map[y as usize][x as usize] { '#' => { seated += 1; break; }, 'L' => { break; }, ...
#[inline] pub fn count_visible(&self, x: usize, y: usize) -> u8 { let mut seated = 0; let ymax = self.map.len() as i64; let xmax = self.map[0].len() as i64;
random_line_split
11.rs
// SPDX-License-Identifier: MIT use clap::{Arg, App}; static DIRECTIONS : [(i64,i64); 8] = [ (-1,-1), ( 0,-1), ( 1,-1), (-1, 0), ( 1, 0), (-1, 1), ( 0, 1), ( 1, 1), ]; #[derive(Clone)] pub struct Floorplan { pub map: Vec<Vec<char>>, } impl Floorplan { pub fn new() -> Floorplan { ...
#[test] fn test2() { let mut plan = Floorplan::load("11.in"); while plan.step2() { } assert_eq!(plan.count(&'#'), 2257); } }
{ let mut plan = Floorplan::load("11.in"); while plan.step1() { } assert_eq!(plan.count(&'#'), 2476); }
identifier_body
context.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 style is calculated. #![deny(missing_docs)] use animation::Animation; use app_units:...
} } /// Creates a task to set the selector flags on an element. pub fn set_selector_flags(el: E, flags: ElementSelectorFlags) -> Self { use self::SequentialTask::*; SetSelectorFlags(unsafe { SendElement::new(el) }, flags) } /// Creates a task to update CSS Animations on a ...
{ unsafe { el.update_animations(pseudo.as_ref()) }; }
conditional_block
context.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 style is calculated. #![deny(missing_docs)] use animation::Animation; use app_units:...
SetSelectorFlags(unsafe { SendElement::new(el) }, flags) } /// Creates a task to update CSS Animations on a given (pseudo-)element. pub fn update_animations(el: E, pseudo: Option<PseudoElement>) -> Self { use self::SequentialTask::*; UpdateAnimations(unsafe { SendElement::new(el) },...
/// Creates a task to set the selector flags on an element. pub fn set_selector_flags(el: E, flags: ElementSelectorFlags) -> Self { use self::SequentialTask::*;
random_line_split
context.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 style is calculated. #![deny(missing_docs)] use animation::Animation; use app_units:...
{ /// The total number of elements traversed. pub elements_traversed: u32, /// The number of elements where has_styles() went from false to true. pub elements_styled: u32, /// The number of elements for which we performed selector matching. pub elements_matched: u32, /// The number of cache...
TraversalStatistics
identifier_name
context.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 style is calculated. #![deny(missing_docs)] use animation::Animation; use app_units:...
/// Notes when the style system finishes traversing an element. pub fn end_element(&mut self, element: E) { debug_assert!(self.current_element_info.is_some()); debug_assert!(self.current_element_info.as_ref().unwrap().element == element.as_node().opaque()); self.c...
{ debug_assert!(self.current_element_info.is_none()); self.current_element_info = Some(CurrentElementInfo { element: element.as_node().opaque(), is_initial_style: !data.has_styles(), }); }
identifier_body
mod.rs
mod bunser; mod map; mod read; mod reentrant; mod seq; mod template; #[cfg(test)] mod test; mod variant; use std::io; use std::str; use serde::de; use crate::errors::*; use crate::header::*; use self::bunser::{Bunser, PduInfo}; use self::read::{DeRead, Reference, SliceRead}; use self::reentrant::ReentrantLimit; pu...
(read: R) -> Result<Self> { let mut bunser = Bunser::new(read); let pdu_info = bunser.read_pdu()?; Ok(Deserializer { bunser, pdu_info, remaining_depth: ReentrantLimit::new(128), }) } /// This method must be called after a value has been fully ...
new
identifier_name
mod.rs
mod bunser; mod map; mod read; mod reentrant; mod seq; mod template; #[cfg(test)] mod test; mod variant; use std::io; use std::str; use serde::de; use crate::errors::*; use crate::header::*; use self::bunser::{Bunser, PduInfo}; use self::read::{DeRead, Reference, SliceRead}; use self::reentrant::ReentrantLimit; pu...
pub fn from_reader<R, T>(rdr: R) -> Result<T> where R: io::Read, T: de::DeserializeOwned, { from_trait(read::IoRead::new(rdr)) } impl<'de, R> Deserializer<R> where R: DeRead<'de>, { pub fn new(read: R) -> Result<Self> { let mut bunser = Bunser::new(read); let pdu_info = bunser.rea...
{ from_trait(SliceRead::new(slice)) }
identifier_body
mod.rs
mod bunser; mod map; mod read; mod reentrant; mod seq; mod template; #[cfg(test)] mod test; mod variant; use std::io; use std::str; use serde::de; use crate::errors::*; use crate::header::*; use self::bunser::{Bunser, PduInfo}; use self::read::{DeRead, Reference, SliceRead}; use self::reentrant::ReentrantLimit; pu...
} /// This method must be called after a value has been fully deserialized. pub fn end(&self) -> Result<()> { self.bunser.end(&self.pdu_info) } #[inline] pub fn capabilities(&self) -> u32 { self.pdu_info.bser_capabilities } fn parse_value<V>(&mut self, visitor: V) -> R...
pdu_info, remaining_depth: ReentrantLimit::new(128), })
random_line_split
shell.rs
use std::env; use std::io::stdin; use std::path::{Path, PathBuf}; use std::process::{Command, Stdio}; struct Shell { cmd_prompt: String, cwd: PathBuf } impl Shell { fn
(prompt_str: &str, cwd: PathBuf) -> Shell { Shell { cmd_prompt: prompt_str.to_owned(), cwd: cwd } } fn start(&mut self) { let stdin = stdin(); loop { println!("{}", self.cmd_prompt); let mut line = String::new(); stdin...
new
identifier_name
shell.rs
use std::env; use std::io::stdin; use std::path::{Path, PathBuf}; use std::process::{Command, Stdio}; struct Shell { cmd_prompt: String, cwd: PathBuf } impl Shell { fn new(prompt_str: &str, cwd: PathBuf) -> Shell { Shell { cmd_prompt: prompt_str.to_owned(), cwd: cwd ...
fn run_cmd(&mut self, cmd: String, argv: Vec<String>) { match &*cmd { "\u{1F697}" => self.cd(argv), "\u{1F4CD}" => self.pwd(), "\u{1F50D}" => self.execute_program("ls".to_string(), argv), "\u{1F431}" => self.execute_program("cat".to_string(), argv), ...
{ let mut arg_vec = Vec::new(); let mut cmd = String::new(); for (index, raw_s) in cmd_line.split("\u{1F345}").enumerate() { let s = raw_s.trim(); if s == "" { continue; } if index == 0 { cmd = s.to_owned(); } else { arg_vec.push(s.to_owned()); } } ...
identifier_body
shell.rs
use std::env; use std::io::stdin; use std::path::{Path, PathBuf}; use std::process::{Command, Stdio}; struct Shell { cmd_prompt: String, cwd: PathBuf } impl Shell { fn new(prompt_str: &str, cwd: PathBuf) -> Shell { Shell { cmd_prompt: prompt_str.to_owned(), cwd: cwd ...
Shell::new("\u{1f41a} ", path).start(); }
random_line_split
memvis.rs
//! Memory visualization use sdl2; use sdl2::mouse::MouseButton; use sdl2::pixels::*; use sdl2::rect::{Point, Rect}; use sdl2::surface::Surface; use std::num::Wrapping; use super::utility::Drawable; use crate::cpu::constants::CpuState; use crate::cpu::constants::MemAddr; use crate::io::constants::*; //use cpu::memvi...
{ let pc = pc as usize; let ref mem = cpu.mem; let b1 = mem[pc + 1]; let b2 = mem[pc + 2]; let (mnem, _) = disasm::pp_opcode(mem[pc] as u8, b1 as u8, b2 as u8, pc as u16); let nn = byte_to_u16(b1, b2); println!( "${:04X} {:16} 0x{:02X} 0x{:02X} 0x{:02X} 0x{:04X}", pc, mnem, m...
identifier_body
memvis.rs
//! Memory visualization use sdl2; use sdl2::mouse::MouseButton; use sdl2::pixels::*; use sdl2::rect::{Point, Rect}; use sdl2::surface::Surface; use std::num::Wrapping; use super::utility::Drawable; use crate::cpu::constants::CpuState; use crate::cpu::constants::MemAddr; use crate::io::constants::*; //use cpu::memvi...
Err(_) => error!("Cannot draw point at {:?}", addr_to_point(addr)), } } CpuEvent::Jump { from: src, to: dst } => { renderer.set_draw_color(Color::RGBA(200, 200, 0, colval)); let sr...
let (r, g, b) = mix_color(colval, colval, scale_col(colval, val), 0, 0, 0); renderer.set_draw_color(Color::RGB(r, g, b)); match renderer.draw_point(addr_to_point(addr)) { Ok(_) => (),
random_line_split
memvis.rs
//! Memory visualization use sdl2; use sdl2::mouse::MouseButton; use sdl2::pixels::*; use sdl2::rect::{Point, Rect}; use sdl2::surface::Surface; use std::num::Wrapping; use super::utility::Drawable; use crate::cpu::constants::CpuState; use crate::cpu::constants::MemAddr; use crate::io::constants::*; //use cpu::memvi...
<T>(renderer: &mut sdl2::render::Canvas<T>, gameboy: &Cpu) where T: sdl2::render::RenderTarget, { // TODO: can be used to do partial "smart" redraw, and speed thing up. // But event logging itself is extremely slow renderer.set_blend_mode(sdl2::render::BlendMode::Add); let event_logger = match gam...
draw_memory_events
identifier_name
lib.rs
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version....
{ let t = format!("{} {}", Colour::Red.bold().paint("test"), Colour::White.normal().paint("again")); let after = kill_color(&t); assert_eq!(after, "test again"); }
identifier_body