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
test.rs
use std::collections::VecDeque; use super::{parse, BinaryOperator, Expression, Operand, Statement, Type}; use scanner::Scanner; #[test] fn example_program_2() { let source = r#" var nTimes : int := 0; print "How many times?"; read nTimes; var x : int; for x in 0..nTimes-1 do print x; print " : Hello, World...
Statement::Read("nTimes".to_string()), Statement::Declaration("x".to_string(), Type::Int, None), Statement::For( "x".to_string(), Expression::Singleton(Operand::Int(0.into())), Expression::Binary( Operand::Identifier("nTimes".to_string()), ...
random_line_split
test.rs
use std::collections::VecDeque; use super::{parse, BinaryOperator, Expression, Operand, Statement, Type}; use scanner::Scanner; #[test] fn example_program_2()
Statement::Print(Expression::Singleton(Operand::StringLiteral( "How many times?".to_string(), ))), Statement::Read("nTimes".to_string()), Statement::Declaration("x".to_string(), Type::Int, None), Statement::For( "x".to_string(), Expression::Sin...
{ let source = r#" var nTimes : int := 0; print "How many times?"; read nTimes; var x : int; for x in 0..nTimes-1 do print x; print " : Hello, World!\n"; end for; assert (x = nTimes);"#; let mut scanner = Scanner::new(); let mut tokens = VecDeque::new(); scanner.scan(source, &mut tokens); ...
identifier_body
test.rs
use std::collections::VecDeque; use super::{parse, BinaryOperator, Expression, Operand, Statement, Type}; use scanner::Scanner; #[test] fn
() { let source = r#" var nTimes : int := 0; print "How many times?"; read nTimes; var x : int; for x in 0..nTimes-1 do print x; print " : Hello, World!\n"; end for; assert (x = nTimes);"#; let mut scanner = Scanner::new(); let mut tokens = VecDeque::new(); scanner.scan(source, &mut tokens); ...
example_program_2
identifier_name
table.rs
extern crate serde_json; extern crate term; use self::term::{Attr, color}; use prettytable::Table; use prettytable::row::Row; use prettytable::cell::Cell; pub fn print_list_table(rows: &Vec<serde_json::Value>, headers: &[(&str, &str)], empty_msg: &str) { if rows.is_empty() { return println_succ!("{}", emp...
Cell::new(&value) }) .collect::<Vec<Cell>>(); table.add_row(Row::new(columns)); }
{ value = row[key].as_object().unwrap() .iter() .map(|(key, value)| format!("{}:{}", key, value)) .collect::<Vec<String>>() .join(","); value = format!("{{{}}}", value) }
conditional_block
table.rs
extern crate serde_json; extern crate term; use self::term::{Attr, color}; use prettytable::Table; use prettytable::row::Row; use prettytable::cell::Cell; pub fn print_list_table(rows: &Vec<serde_json::Value>, headers: &[(&str, &str)], empty_msg: &str) { if rows.is_empty() { return println_succ!("{}", emp...
(table: &mut Table, headers: &[(&str, &str)]) { let tittles = headers.iter().clone() .map(|&(_, ref header)| Cell::new(header) .with_style(Attr::Bold) .with_style(Attr::ForegroundColor(color::GREEN)) ).collect::<Vec<Cell>>(); table.add_row(Row::new(tittles)); } pub fn prin...
print_header
identifier_name
table.rs
use prettytable::row::Row; use prettytable::cell::Cell; pub fn print_list_table(rows: &Vec<serde_json::Value>, headers: &[(&str, &str)], empty_msg: &str) { if rows.is_empty() { return println_succ!("{}", empty_msg); } let mut table = Table::new(); print_header(&mut table, headers); for r...
extern crate serde_json; extern crate term; use self::term::{Attr, color}; use prettytable::Table;
random_line_split
table.rs
extern crate serde_json; extern crate term; use self::term::{Attr, color}; use prettytable::Table; use prettytable::row::Row; use prettytable::cell::Cell; pub fn print_list_table(rows: &Vec<serde_json::Value>, headers: &[(&str, &str)], empty_msg: &str) { if rows.is_empty() { return println_succ!("{}", emp...
pub fn print_header(table: &mut Table, headers: &[(&str, &str)]) { let tittles = headers.iter().clone() .map(|&(_, ref header)| Cell::new(header) .with_style(Attr::Bold) .with_style(Attr::ForegroundColor(color::GREEN)) ).collect::<Vec<Cell>>(); table.add_row(Row::new(titt...
{ let mut table = Table::new(); print_header(&mut table, headers); print_row(&mut table, row, headers); table.printstd(); }
identifier_body
expr-match-generic-unique2.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...
fn test_vec() { fn compare_box(v1: Box<isize>, v2: Box<isize>) -> bool { return v1 == v2; } test_generic::<Box<isize>, _>(box 1, compare_box); } pub fn main() { test_vec(); }
true => expected.clone(), _ => panic!("wat") }; assert!(eq(expected, actual)); }
random_line_split
expr-match-generic-unique2.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
{ test_vec(); }
identifier_body
expr-match-generic-unique2.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...
<T: Clone, F>(expected: T, eq: F) where F: FnOnce(T, T) -> bool { let actual: T = match true { true => expected.clone(), _ => panic!("wat") }; assert!(eq(expected, actual)); } fn test_vec() { fn compare_box(v1: Box<isize>, v2: Box<isize>) -> bool { return v1 == v2; } test_generic::<...
test_generic
identifier_name
tuple.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 ...
//! assert!(b == c); //! //! let d : (u32, f32) = Default::default(); //! assert_eq!(d, (0, 0.0f32)); //! ``` #![doc(primitive = "tuple")] #![stable(feature = "rust1", since = "1.0.0")]
//! let c = b.clone();
random_line_split
main.rs
extern crate kiss3d; extern crate nalgebra as na; extern crate time; extern crate rustc_serialize; use kiss3d::window::Window; use kiss3d::light::Light; mod leg; mod constants; use leg::Leg; use std::fs::{File}; use std::io::prelude::{Read}; use std::io::Write; use std::vec::Vec; use std::f32::consts::PI; use rus...
}; //Reading the file into a string let mut s = String::new(); file.read_to_string(&mut s).unwrap(); //let json_data = json::Json::from_str(&s).unwrap(); result = match json::decode(&s) { Ok(val) => { is_done = true; ...
{ let file_dir = String::from("/tmp/hexsim"); let filepath = file_dir.clone() + "/leg_input"; try_with_yolo!(std::fs::create_dir(&file_dir)); //Opening the file //let mut file = None; let mut is_done = false; let mut result: Vec<LegTarget> = vec!(); while !is_done { le...
identifier_body
main.rs
extern crate kiss3d; extern crate nalgebra as na; extern crate time; extern crate rustc_serialize; use kiss3d::window::Window; use kiss3d::light::Light; mod leg; mod constants; use leg::Leg; use std::fs::{File}; use std::io::prelude::{Read}; use std::io::Write; use std::vec::Vec; use std::f32::consts::PI; use rus...
window.set_light(Light::StickToCamera); let mut robot = Robot::new(&mut window); let mut old_time = time::precise_time_s() as f32; while window.render() { let new_time = time::precise_time_s() as f32; let delta_time = (new_time - old_time) * constants::TIME_MODIFIER; old_...
} fn main() { let mut window = Window::new("Kiss3d: cube");
random_line_split
main.rs
extern crate kiss3d; extern crate nalgebra as na; extern crate time; extern crate rustc_serialize; use kiss3d::window::Window; use kiss3d::light::Light; mod leg; mod constants; use leg::Leg; use std::fs::{File}; use std::io::prelude::{Read}; use std::io::Write; use std::vec::Vec; use std::f32::consts::PI; use rus...
(&self) { { let mut file = File::create("/tmp/hexsim/servo_states").unwrap(); let mut result = String::from(""); for leg in &self.legs { for status in leg.is_still_moving() { result += match status ...
write_angles_done
identifier_name
rtctrackevent.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::codegen::Bindings::EventBinding::EventBinding::EventMethods; use crate::dom::bindings::...
} impl RTCTrackEventMethods for RTCTrackEvent { // https://w3c.github.io/webrtc-pc/#dom-rtctrackevent-track fn Track(&self) -> DomRoot<MediaStreamTrack> { DomRoot::from_ref(&*self.track) } // https://dom.spec.whatwg.org/#dom-event-istrusted fn IsTrusted(&self) -> bool { self.event...
{ Ok(RTCTrackEvent::new( &window.global(), Atom::from(type_), init.parent.bubbles, init.parent.cancelable, &init.track, )) }
identifier_body
rtctrackevent.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::codegen::Bindings::EventBinding::EventBinding::EventMethods; use crate::dom::bindings::...
pub fn new( global: &GlobalScope, type_: Atom, bubbles: bool, cancelable: bool, track: &MediaStreamTrack, ) -> DomRoot<RTCTrackEvent> { let trackevent = reflect_dom_object( Box::new(RTCTrackEvent::new_inherited(&track)), global, ...
event: Event::new_inherited(), track: Dom::from_ref(track), } }
random_line_split
rtctrackevent.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::codegen::Bindings::EventBinding::EventBinding::EventMethods; use crate::dom::bindings::...
(&self) -> bool { self.event.IsTrusted() } }
IsTrusted
identifier_name
constellation_msg.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! The high-level interface from script to constellation. Using this abstract interface helps //! reduce coupling...
pub trait ConvertPipelineIdToWebRender { fn to_webrender(&self) -> webrender_traits::PipelineId; } pub trait ConvertPipelineIdFromWebRender { fn from_webrender(&self) -> PipelineId; } impl ConvertPipelineIdToWebRender for PipelineId { fn to_webrender(&self) -> webrender_traits::PipelineId { let P...
} #[derive(Clone, PartialEq, Eq, Copy, Hash, Debug, Deserialize, Serialize, HeapSizeOf)] pub struct SubpageId(pub u32);
random_line_split
constellation_msg.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! The high-level interface from script to constellation. Using this abstract interface helps //! reduce coupling...
() -> (IpcReceiver<T>, ConstellationChan<T>) { let (chan, port) = ipc::channel().unwrap(); (port, ConstellationChan(chan)) } } impl<T: Serialize + Deserialize> Clone for ConstellationChan<T> { fn clone(&self) -> ConstellationChan<T> { ConstellationChan(self.0.clone()) } } // We pas...
new
identifier_name
joiner.rs
use std::os; use std::io::File; //use std::ops::BitXor; fn main() { let args: ~[~str] = os::args(); if args.len()!= 3 { println!("Usage: {:s} <intputfile>", args[0]); } else
let fname_a = args[1].clone(); let path_a = Path::new(fname_a.clone()); let msg_file_a = File::open(&path_a); let fname_b = args[2]; let path_b = Path::new(fname_b.clone()); let msg_file_b = File::open(&path_b); match(msg_file_a, msg_file_b) { (Some(mut msg_a), Some(mut msg_b)) => { let msg_...
{
random_line_split
joiner.rs
use std::os; use std::io::File; //use std::ops::BitXor; fn main() { let args: ~[~str] = os::args(); if args.len()!= 3 { println!("Usage: {:s} <intputfile>", args[0]); } else { let fname_a = args[1].clone(); let path_a = Path::new(fname_a.clone()); let msg_file_a = File::open(&path_a); let fname_b = ...
(a: &[u8], b: &[u8])-> ~[u8] { let mut ret = ~[]; for i in range(0, a.len()) { ret.push(a[i] ^ b[i]); } ret } fn joiner(mut join: File, msg_bytes_a: &[u8], msg_bytes_b: &[u8]) { let unencrypted_bytes = xor(msg_bytes_a, msg_bytes_b); join.write((unencrypted_bytes)); }
xor
identifier_name
joiner.rs
use std::os; use std::io::File; //use std::ops::BitXor; fn main() { let args: ~[~str] = os::args(); if args.len()!= 3 { println!("Usage: {:s} <intputfile>", args[0]); } else { let fname_a = args[1].clone(); let path_a = Path::new(fname_a.clone()); let msg_file_a = File::open(&path_a); let fname_b = ...
, None => fail!("Error opening output files!"), } }, (_, _) => fail!("Error opening message file: {:s}", fname_a) } } } fn xor(a: &[u8], b: &[u8])-> ~[u8] { let mut ret = ~[]; for i in range(0, a.len()) { ret.push(a[i] ^ b[i]); } ret } fn joiner(mut join: File, msg_bytes_a: &[u8], msg_byt...
{ joiner(join, msg_bytes_a, msg_bytes_b); }
conditional_block
joiner.rs
use std::os; use std::io::File; //use std::ops::BitXor; fn main() { let args: ~[~str] = os::args(); if args.len()!= 3 { println!("Usage: {:s} <intputfile>", args[0]); } else { let fname_a = args[1].clone(); let path_a = Path::new(fname_a.clone()); let msg_file_a = File::open(&path_a); let fname_b = ...
{ let unencrypted_bytes = xor(msg_bytes_a, msg_bytes_b); join.write((unencrypted_bytes)); }
identifier_body
client.rs
// Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0. use std::future::Future; use crate::call::client::{ CallOption, ClientCStreamReceiver, ClientCStreamSender, ClientDuplexReceiver, ClientDuplexSender, ClientSStreamReceiver, ClientUnaryReceiver, }; use crate::call::{Call, Method}; use crate::ch...
/// Spawn the future into current gRPC poll thread. /// /// This can reduce a lot of context switching, but please make /// sure there is no heavy work in the future. pub fn spawn<F>(&self, f: F) where F: Future<Output = ()> + Send +'static, { let kicker = self.kicker.clone...
{ Call::duplex_streaming(&self.channel, method, opt) }
identifier_body
client.rs
// Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0. use std::future::Future; use crate::call::client::{ CallOption, ClientCStreamReceiver, ClientCStreamSender, ClientDuplexReceiver, ClientDuplexSender, ClientSStreamReceiver, ClientUnaryReceiver, }; use crate::call::{Call, Method}; use crate::ch...
/// Create an asynchronized client streaming call. /// /// Client can send a stream of requests and server responds with a single response. pub fn client_streaming<Req, Resp>( &self, method: &Method<Req, Resp>, opt: CallOption, ) -> Result<(ClientCStreamSender<Req>, ClientCSt...
random_line_split
client.rs
// Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0. use std::future::Future; use crate::call::client::{ CallOption, ClientCStreamReceiver, ClientCStreamSender, ClientDuplexReceiver, ClientDuplexSender, ClientSStreamReceiver, ClientUnaryReceiver, }; use crate::call::{Call, Method}; use crate::ch...
{ channel: Channel, // Used to kick its completion queue. kicker: Kicker, } impl Client { /// Initialize a new [`Client`]. pub fn new(channel: Channel) -> Client { let kicker = channel.create_kicker().unwrap(); Client { channel, kicker } } /// Create a synchronized unary R...
Client
identifier_name
options.rs
use scaly::containers::Ref; use scaly::memory::Region; use scaly::Equal; use scaly::Page; use scaly::{Array, String, Vector}; pub struct
{ pub files: Ref<Vector<String>>, pub output_name: Option<String>, pub directory: Option<String>, pub repl: bool, } impl Options { pub fn parse_arguments( _pr: &Region, _rp: *mut Page, _ep: *mut Page, arguments: Ref<Vector<String>>, ) -> Ref<Options> { l...
Options
identifier_name
options.rs
use scaly::containers::Ref; use scaly::memory::Region; use scaly::Equal; use scaly::Page; use scaly::{Array, String, Vector}; pub struct Options { pub files: Ref<Vector<String>>, pub output_name: Option<String>, pub directory: Option<String>, pub repl: bool, } impl Options { pub fn parse_arguments...
if (arg.unwrap()).equals(&String::from_string_slice(_r_1.page, "-o")) { arg = args.next(); output_name = Some(*arg.unwrap()); continue; } } { let _r_1 = Region::create(&_r); ...
break; } { let _r_1 = Region::create(&_r);
random_line_split
options.rs
use scaly::containers::Ref; use scaly::memory::Region; use scaly::Equal; use scaly::Page; use scaly::{Array, String, Vector}; pub struct Options { pub files: Ref<Vector<String>>, pub output_name: Option<String>, pub directory: Option<String>, pub repl: bool, } impl Options { pub fn parse_arguments...
} { let _r_1 = Region::create(&_r); if (arg.unwrap()).equals(&String::from_string_slice(_r_1.page, "-r")) { repl = true; continue; } } files.add(*arg.unwrap()); } R...
{ arg = args.next(); directory = Some(*arg.unwrap()); continue; }
conditional_block
mod.rs
use bindgen::callbacks::*; #[derive(Debug)] struct EnumVariantRename; impl ParseCallbacks for EnumVariantRename { fn enum_variant_name( &self, _enum_name: Option<&str>, original_variant_name: &str, _variant_value: EnumVariantValue, ) -> Option<String> { Some(format!("RE...
( &self, _name: &str, derive_trait: DeriveTrait, ) -> Option<ImplementsTrait> { if derive_trait == DeriveTrait::Hash { Some(ImplementsTrait::No) } else { Some(ImplementsTrait::Yes) } } } pub fn lookup(cb: &str) -> Box<dyn ParseCallbacks> {...
blocklisted_type_implements_trait
identifier_name
mod.rs
use bindgen::callbacks::*; #[derive(Debug)] struct EnumVariantRename; impl ParseCallbacks for EnumVariantRename { fn enum_variant_name( &self, _enum_name: Option<&str>, original_variant_name: &str, _variant_value: EnumVariantValue, ) -> Option<String> { Some(format!("RE...
} pub fn lookup(cb: &str) -> Box<dyn ParseCallbacks> { match cb { "enum-variant-rename" => Box::new(EnumVariantRename), "blocklisted-type-implements-trait" => { Box::new(BlocklistedTypeImplementsTrait) } _ => panic!("Couldn't find name ParseCallbacks: {}", cb), } }
{ if derive_trait == DeriveTrait::Hash { Some(ImplementsTrait::No) } else { Some(ImplementsTrait::Yes) } }
identifier_body
mod.rs
use bindgen::callbacks::*; #[derive(Debug)] struct EnumVariantRename; impl ParseCallbacks for EnumVariantRename { fn enum_variant_name( &self, _enum_name: Option<&str>, original_variant_name: &str, _variant_value: EnumVariantValue, ) -> Option<String> { Some(format!("RE...
impl ParseCallbacks for BlocklistedTypeImplementsTrait { fn blocklisted_type_implements_trait( &self, _name: &str, derive_trait: DeriveTrait, ) -> Option<ImplementsTrait> { if derive_trait == DeriveTrait::Hash { Some(ImplementsTrait::No) } else { ...
} #[derive(Debug)] struct BlocklistedTypeImplementsTrait;
random_line_split
duplex.rs
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
(&self) -> R { self.rx.recv() } pub fn try_recv(&self) -> Result<R, comm::TryRecvError> { self.rx.try_recv() } pub fn recv_opt(&self) -> Result<R, ()> { self.rx.recv_opt() } } #[cfg(test)] mod test { use std::prelude::*; use comm::{duplex}; #[test] pub fn du...
recv
identifier_name
duplex.rs
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
// Allow these methods to be used without import: impl<S:Send,R:Send> DuplexStream<S, R> { pub fn send(&self, x: S) { self.tx.send(x) } pub fn send_opt(&self, x: S) -> Result<(), S> { self.tx.send_opt(x) } pub fn recv(&self) -> R { self.rx.recv() } pub fn try_recv(&s...
random_line_split
duplex.rs
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
pub fn send_opt(&self, x: S) -> Result<(), S> { self.tx.send_opt(x) } pub fn recv(&self) -> R { self.rx.recv() } pub fn try_recv(&self) -> Result<R, comm::TryRecvError> { self.rx.try_recv() } pub fn recv_opt(&self) -> Result<R, ()> { self.rx.recv_opt() } ...
{ self.tx.send(x) }
identifier_body
icosphere.rs
use std::collections::HashMap; use std::mem; use scene::Vertex; fn
(pos: [f32; 3]) -> Vertex { use std::f32::consts::{PI}; let u = pos[0].atan2(pos[2]) / (-2.0 * PI); let u = if u < 0. { u + 1. } else { u }; let v = pos[1].asin() / PI + 0.5; Vertex::new(pos, [u, v]) } pub fn generate(recursion: u16) -> (Vec<Vertex>, Vec<u16>) { let face_count = 20 * 4usize.p...
vertex
identifier_name
icosphere.rs
use std::collections::HashMap; use std::mem; use scene::Vertex; fn vertex(pos: [f32; 3]) -> Vertex { use std::f32::consts::{PI}; let u = pos[0].atan2(pos[2]) / (-2.0 * PI); let u = if u < 0. { u + 1. } else { u }; let v = pos[1].asin() / PI + 0.5; Vertex::new(pos, [u, v]) } pub fn generate(recur...
vertex([ 0.0, u, v]), vertex([ 0.0, -u, -v]), vertex([ 0.0, u, -v]), vertex([ v, 0.0, -u]), vertex([ v, 0.0, u]), vertex([ -v, 0.0, -u]), vertex([ -v, 0.0, u]), ]); let mut index_data: Vec<u16> = Vec::with_capacity(index_count); index_data.extend_fro...
{ let face_count = 20 * 4usize.pow(recursion as u32); let edge_count = 3 * face_count / 2; // Euler's formula let vertex_count = 2 + edge_count - face_count; let index_count = face_count * 3; let t = (1.0 + 5.0_f32.sqrt()) / 2.0; let n = (1. + t * t).sqrt(); let u = 1. / n; let v =...
identifier_body
icosphere.rs
use std::collections::HashMap; use std::mem; use scene::Vertex; fn vertex(pos: [f32; 3]) -> Vertex { use std::f32::consts::{PI}; let u = pos[0].atan2(pos[2]) / (-2.0 * PI); let u = if u < 0. { u + 1. } else
; let v = pos[1].asin() / PI + 0.5; Vertex::new(pos, [u, v]) } pub fn generate(recursion: u16) -> (Vec<Vertex>, Vec<u16>) { let face_count = 20 * 4usize.pow(recursion as u32); let edge_count = 3 * face_count / 2; // Euler's formula let vertex_count = 2 + edge_count - face_count; let index_...
{ u }
conditional_block
icosphere.rs
use std::collections::HashMap; use std::mem; use scene::Vertex; fn vertex(pos: [f32; 3]) -> Vertex { use std::f32::consts::{PI}; let u = pos[0].atan2(pos[2]) / (-2.0 * PI); let u = if u < 0. { u + 1. } else { u }; let v = pos[1].asin() / PI + 0.5; Vertex::new(pos, [u, v]) } pub fn generate(recur...
5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8, // 5 faces around point 3 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9, // 5 adjacent faces 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1, ]); ...
// 5 adjacent faces 1, 5, 9,
random_line_split
lib.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::collections::BTreeMap; use std::collections::HashMap; use clidispatch::global_flags::HgGlobalOpts; use cliparser::alias::expand_a...
if tuple.len(py) < 3 { let msg = format!("flag defintion requires at least 3 items"); return Err(PyErr::new::<exc::ValueError, _>(py, msg)); } let short: String = tuple.get_item(py, 0).extract(py)?; let long: String = tuple.get_item(py, 1).extract(py)?; le...
fn extract(py: Python, obj: &'s PyObject) -> PyResult<Self> { let tuple: PyTuple = obj.extract(py)?;
random_line_split
lib.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::collections::BTreeMap; use std::collections::HashMap; use clidispatch::global_flags::HgGlobalOpts; use cliparser::alias::expand_a...
ParseError::OptionAmbiguous { option_name, possibilities, } => { return PyErr::new::<exceptions::OptionAmbiguous, _>( py, (msg, option_name, possibilities), ); } ParseError::AmbiguousCommand { co...
{ return PyErr::new::<exceptions::OptionArgumentInvalid, _>( py, (msg, option_name, given, expected), ); }
conditional_block
lib.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::collections::BTreeMap; use std::collections::HashMap; use clidispatch::global_flags::HgGlobalOpts; use cliparser::alias::expand_a...
(py: Python, package: &str) -> PyResult<PyModule> { let name = [package, "cliparser"].join("."); let m = PyModule::new(py, &name)?; m.add(py, "earlyparse", py_fn!(py, early_parse(args: Vec<String>)))?; m.add(py, "parseargs", py_fn!(py, parse_args(args: Vec<String>)))?; m.add( py, "pa...
init_module
identifier_name
lib.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::collections::BTreeMap; use std::collections::HashMap; use clidispatch::global_flags::HgGlobalOpts; use cliparser::alias::expand_a...
continue; } let is_debug = name.starts_with("debug"); let i = command_map.len() as isize; command_map.insert(name, if is_debug { -i } else { i }); } } let lookup = move |name: &str| { if name.contains(":") { return None...
{ let cfg = &config.get_cfg(py); if !strict && !args.is_empty() { // Expand args[0] from a prefix to a full command name let mut command_map = BTreeMap::new(); for (i, name) in command_names.into_iter().enumerate() { let i: isize = i as isize + 1; // avoid using 0 ...
identifier_body
seh.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT.
// <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. //! Win64 SEH (see http://msdn.microsoft.com/en-us/library/1eyas8tf.aspx) //! //! On Windows (currently only on MSVC), the default exception handling //! ...
// // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
random_line_split
seh.rs
// Copyright 2015 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 ...
{ unsafe { ((*(*eh_ptrs).ExceptionRecord).ExceptionCode == RUST_PANIC) as i32 } }
identifier_body
seh.rs
// Copyright 2015 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 ...
{} const EXCEPTION_MAXIMUM_PARAMETERS: usize = 15; pub unsafe fn panic(data: Box<Any + Send +'static>) ->! { // See module docs above for an explanation of why `data` is stored in a // thread local instead of being passed as an argument to the // `RaiseException` function (which can in theory carry along...
_EXCEPTION_RECORD
identifier_name
main.rs
extern crate piston; extern crate graphics; extern crate glutin_window; extern crate opengl_graphics; use piston::window::WindowSettings; use piston::event_loop::*; use piston::input::*; use glutin_window::GlutinWindow as Window; use opengl_graphics::{ GlGraphics, OpenGL }; pub struct
{ gl: GlGraphics, // OpenGL drawing backend. rotation: f64 // Rotation for the square. } impl App { fn render(&mut self, args: &RenderArgs) { use graphics::*; const GREEN: [f32; 4] = [0.0, 1.0, 0.0, 1.0]; const RED: [f32; 4] = [1.0, 0.0, 0.0, 1.0]; let square = rectan...
App
identifier_name
main.rs
extern crate piston; extern crate graphics; extern crate glutin_window; extern crate opengl_graphics; use piston::window::WindowSettings; use piston::event_loop::*; use piston::input::*; use glutin_window::GlutinWindow as Window; use opengl_graphics::{ GlGraphics, OpenGL }; pub struct App { gl: GlGraphics, // Ope...
if let Some(u) = e.update_args() { app.update(&u); } } }
{ app.render(&r); }
conditional_block
main.rs
extern crate piston; extern crate graphics; extern crate glutin_window; extern crate opengl_graphics; use piston::window::WindowSettings; use piston::event_loop::*; use piston::input::*; use glutin_window::GlutinWindow as Window; use opengl_graphics::{ GlGraphics, OpenGL }; pub struct App { gl: GlGraphics, // Ope...
rectangle(RED, square, transform, gl); }); } fn update(&mut self, args: &UpdateArgs) { // Rotate 2 radians per second. self.rotation += 2.0 * args.dt; } } fn main() { // Change this to OpenGL::V2_1 if not working. // let opengl = OpenGL::V3_2; let opengl = Ope...
{ use graphics::*; const GREEN: [f32; 4] = [0.0, 1.0, 0.0, 1.0]; const RED: [f32; 4] = [1.0, 0.0, 0.0, 1.0]; let square = rectangle::square(0.0, 0.0, 50.0); let rotation = self.rotation; let (x, y) = ((args.width / 2) as f64, (args.height / 2) as...
identifier_body
main.rs
extern crate piston; extern crate graphics; extern crate glutin_window; extern crate opengl_graphics; use piston::window::WindowSettings; use piston::event_loop::*; use piston::input::*; use glutin_window::GlutinWindow as Window; use opengl_graphics::{ GlGraphics, OpenGL }; pub struct App { gl: GlGraphics, // Ope...
} } fn main() { // Change this to OpenGL::V2_1 if not working. // let opengl = OpenGL::V3_2; let opengl = OpenGL::V2_1; // Create an Glutin window. let mut window: Window = WindowSettings::new( "spinning-square", [200, 200] ) .opengl(opengl) .exit_on_...
// Rotate 2 radians per second. self.rotation += 2.0 * args.dt;
random_line_split
primitive_list.rs
// Copyright (c) 2013-2015 Sandstorm Development Group, Inc. and contributors // Licensed under the MIT License: // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, inc...
<'a, T> where T: PrimitiveElement { marker : ::std::marker::PhantomData<T>, builder : ListBuilder<'a> } impl <'a, T> Builder<'a, T> where T: PrimitiveElement { pub fn new(builder : ListBuilder<'a>) -> Builder<'a, T> { Builder { builder : builder, marker : ::std::marker::PhantomData } } pub...
Builder
identifier_name
primitive_list.rs
// Copyright (c) 2013-2015 Sandstorm Development Group, Inc. and contributors // Licensed under the MIT License: //
// copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WAR...
// Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
random_line_split
primitive_list.rs
// Copyright (c) 2013-2015 Sandstorm Development Group, Inc. and contributors // Licensed under the MIT License: // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, inc...
} pub struct Builder<'a, T> where T: PrimitiveElement { marker : ::std::marker::PhantomData<T>, builder : ListBuilder<'a> } impl <'a, T> Builder<'a, T> where T: PrimitiveElement { pub fn new(builder : ListBuilder<'a>) -> Builder<'a, T> { Builder { builder : builder, marker : ::std::marker::Phanto...
{ assert!(index < self.len()); PrimitiveElement::get(&self.reader, index) }
identifier_body
eg-enum-use.rs
#![allow(dead_code)] enum HTTPGood { HTTP200, HTTP300, } enum HTTPBad { HTTP400, HTTP500, } fn server_debug() { use HTTPGood::{HTTP200, HTTP300}; // explicitly pick name without manual scoping use HTTPBad::*; // automatically use each name let good = HTTP200; // equivalent to HTTPGood::H...
match bad { HTTP400 => println!("bad client"), HTTP500 => println!("bad server"), } } enum BrowserEvent { // may be unit like Render, Clear, // tuple structs KeyPress(char), LoadFrame(String), // or structs Click { x: i64, y: i64 }, } fn browser_debug(event: Bro...
match good { HTTP200 => println!("okay"), HTTP300 => println!("redirect"), }
random_line_split
eg-enum-use.rs
#![allow(dead_code)] enum HTTPGood { HTTP200, HTTP300, } enum HTTPBad { HTTP400, HTTP500, } fn server_debug() { use HTTPGood::{HTTP200, HTTP300}; // explicitly pick name without manual scoping use HTTPBad::*; // automatically use each name let good = HTTP200; // equivalent to HTTPGood::H...
{ // may be unit like Render, Clear, // tuple structs KeyPress(char), LoadFrame(String), // or structs Click { x: i64, y: i64 }, } fn browser_debug(event: BrowserEvent) { match event { BrowserEvent::Render => println!("render page"), BrowserEvent::Clear => println!(...
BrowserEvent
identifier_name
eg-enum-use.rs
#![allow(dead_code)] enum HTTPGood { HTTP200, HTTP300, } enum HTTPBad { HTTP400, HTTP500, } fn server_debug() { use HTTPGood::{HTTP200, HTTP300}; // explicitly pick name without manual scoping use HTTPBad::*; // automatically use each name let good = HTTP200; // equivalent to HTTPGood::H...
{ server_debug(); let render = BrowserEvent::Render; let clear = BrowserEvent::Clear; let keypress = BrowserEvent::KeyPress('z'); let frame = BrowserEvent::LoadFrame("example.com".to_owned()); // creates an owned String from string slice let click = BrowserEvent::Click {x: 120, y: 240}; bro...
identifier_body
pratparser.rs
enum
{ Atom(String), Cons(String, Vec<S>), } impl std::fmt::Display for S { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { S::Atom(i) => write!(f, "{}", i), S::Cons(head, rest) => { write!(f, "({}", head)?; for s...
S
identifier_name
pratparser.rs
enum S { Atom(String), Cons(String, Vec<S>), } impl std::fmt::Display for S { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { S::Atom(i) => write!(f, "{}", i), S::Cons(head, rest) => { write!(f, "({}", head)?; ...
'[' => { let rhs = expr_bp(lexer, 0); assert_eq!(lexer.next(), Token::Op(']')); S::Cons(op.to_string(), vec![lhs, rhs]) } '(' => { let mut args = vec![expr_bp(lexer, 0)]; w...
lexer.next(); lhs = match op {
random_line_split
domtokenlist.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::attr::Attr; use dom::bindings::codegen::Bindings::DOMTokenListBinding; use dom::bindings::codegen::Bindin...
let attr = attr.r(); attr.value().as_tokens().len() }).unwrap_or(0) as u32 } // https://dom.spec.whatwg.org/#dom-domtokenlist-item fn Item(&self, index: u32) -> Option<DOMString> { self.attribute().and_then(|attr| { let attr = attr.r(); Some(a...
random_line_split
domtokenlist.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::attr::Attr; use dom::bindings::codegen::Bindings::DOMTokenListBinding; use dom::bindings::codegen::Bindin...
} element.r().set_atomic_tokenlist_attribute(&self.local_name, atoms); Ok(()) } // https://dom.spec.whatwg.org/#dom-domtokenlist-remove fn Remove(&self, tokens: Vec<DOMString>) -> ErrorResult { let element = self.element.root(); let mut atoms = element.r().get_token...
{ atoms.push(token); }
conditional_block
domtokenlist.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::attr::Attr; use dom::bindings::codegen::Bindings::DOMTokenListBinding; use dom::bindings::codegen::Bindin...
pub fn new(element: &Element, local_name: &Atom) -> Root<DOMTokenList> { let window = window_from_node(element); reflect_dom_object(box DOMTokenList::new_inherited(element, local_name.clone()), GlobalRef::Window(window.r()), DOMTokenListBinding...
{ DOMTokenList { reflector_: Reflector::new(), element: JS::from_ref(element), local_name: local_name, } }
identifier_body
domtokenlist.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::attr::Attr; use dom::bindings::codegen::Bindings::DOMTokenListBinding; use dom::bindings::codegen::Bindin...
(&self) -> u32 { self.attribute().map(|attr| { let attr = attr.r(); attr.value().as_tokens().len() }).unwrap_or(0) as u32 } // https://dom.spec.whatwg.org/#dom-domtokenlist-item fn Item(&self, index: u32) -> Option<DOMString> { self.attribute().and_then(|attr...
Length
identifier_name
commands.rs
use river::River; pub use river::PeekResult; /// Push command - stateless /// /// Used to push messages to rivers like this: /// /// ``` /// john::PushCommand::new().execute("river_name", "message"); /// ``` pub struct PushCommand; impl PushCommand { /// Constructor ::new() /// /// Creates new instance of...
/// Used to execute push command, specifying a river name and message /// This can be called multiple times with different arguments /// since PushCommand is stateless pub fn execute(&self, river: &str, message: &str) { River::new(river).push(message); } } /// Peek command - stateless ///...
{ PushCommand }
identifier_body
commands.rs
use river::River; pub use river::PeekResult; /// Push command - stateless /// /// Used to push messages to rivers like this: /// /// ``` /// john::PushCommand::new().execute("river_name", "message"); /// ``` pub struct PushCommand; impl PushCommand { /// Constructor ::new() /// /// Creates new instance of...
pub fn execute(&self, river: &str) { River::new(river).destroy(); } }
random_line_split
commands.rs
use river::River; pub use river::PeekResult; /// Push command - stateless /// /// Used to push messages to rivers like this: /// /// ``` /// john::PushCommand::new().execute("river_name", "message"); /// ``` pub struct PushCommand; impl PushCommand { /// Constructor ::new() /// /// Creates new instance of...
(&self, river: &str) { River::new(river).destroy(); } }
execute
identifier_name
day_6.rs
use std::fmt; use std::iter::FromIterator; use std::ops::Add; #[derive(PartialEq)] pub enum List<T> { Empty, Cons(T, Box<List<T>>), } impl <T> List<T> { pub fn empty() -> Self { List::Empty } pub fn head(&self) -> Option<&T> { match self { &List::Empty => None, ...
(&self, formatter: &mut fmt::Formatter) -> fmt::Result { write!(formatter, "{}", self.to_string()) } } impl <T: ToString> ToString for List<T> { fn to_string(&self) -> String { fn internal<E: ToString>(list: &List<E>) -> String { match list { &List::Empty => "".to_ow...
fmt
identifier_name
day_6.rs
use std::fmt; use std::iter::FromIterator; use std::ops::Add; #[derive(PartialEq)] pub enum List<T> { Empty, Cons(T, Box<List<T>>), } impl <T> List<T> { pub fn empty() -> Self
pub fn head(&self) -> Option<&T> { match self { &List::Empty => None, &List::Cons(ref head, _) => Some(&head) } } pub fn tail(self) -> Self { match self { List::Empty => self, List::Cons(_, tail) => *tail } } } impl <T> ...
{ List::Empty }
identifier_body
day_6.rs
use std::fmt; use std::iter::FromIterator; use std::ops::Add; #[derive(PartialEq)] pub enum List<T> { Empty, Cons(T, Box<List<T>>), } impl <T> List<T> { pub fn empty() -> Self { List::Empty }
match self { &List::Empty => None, &List::Cons(ref head, _) => Some(&head) } } pub fn tail(self) -> Self { match self { List::Empty => self, List::Cons(_, tail) => *tail } } } impl <T> Add<T> for List<T> { type Output = Se...
pub fn head(&self) -> Option<&T> {
random_line_split
main.rs
// This example implements the queens problem: // https://en.wikipedia.org/wiki/Eight_queens_puzzle // using an evolutionary algorithm. extern crate rand; extern crate simplelog; // internal crates extern crate darwin_rs; use rand::Rng; use simplelog::{SimpleLogger, LogLevelFilter, Config}; // internal modules use ...
() { println!("Darwin test: queens problem"); let _ = SimpleLogger::init(LogLevelFilter::Info, Config::default()); let queens = SimulationBuilder::<Queens>::new() .fitness(0.0) .threads(2) .add_multiple_populations(make_all_populations(100, 8)) .finalize(); match queens { ...
main
identifier_name
main.rs
// This example implements the queens problem: // https://en.wikipedia.org/wiki/Eight_queens_puzzle // using an evolutionary algorithm. extern crate rand; extern crate simplelog; // internal crates extern crate darwin_rs; use rand::Rng; use simplelog::{SimpleLogger, LogLevelFilter, Config}; // internal modules use ...
// left num_of_collisions += one_trace(board, row, col, 0, -1); // left top num_of_collisions += one_trace(board, row, col, -1, -1); num_of_collisions } fn make_population(count: u32) -> Vec<Queens> { let mut result = Vec::new(); for _ in 0..count { result.push( Que...
{ let mut num_of_collisions = 0; // up num_of_collisions += one_trace(board, row, col, -1, 0); // up right num_of_collisions += one_trace(board, row, col, -1, 1); // right num_of_collisions += one_trace(board, row, col, 0, 1); // right down num_of_collisions += one_trace(board, r...
identifier_body
main.rs
// This example implements the queens problem: // https://en.wikipedia.org/wiki/Eight_queens_puzzle // using an evolutionary algorithm. extern crate rand; extern crate simplelog; // internal crates extern crate darwin_rs; use rand::Rng; use simplelog::{SimpleLogger, LogLevelFilter, Config}; // internal modules use ...
.finalize().unwrap(); result.push(pop); } result } // implement trait functions mutate and calculate_fitness: impl Individual for Queens { fn mutate(&mut self) { let mut rng = rand::thread_rng(); let mut index1: usize = rng.gen_range(0, self.board.len()); let m...
random_line_split
mod.rs
//! Defines the trait implemented by all textured values use std::ops::{Add, Mul}; use film::Colorf; pub use self::image::Image; pub use self::animated_image::AnimatedImage; pub mod image; pub mod animated_image; /// scalars or Colors can be computed on some image texture /// or procedural generator pub trait Text...
impl ConstantColor { pub fn new(val: Colorf) -> ConstantColor { ConstantColor { val: val } } } impl Texture for ConstantColor { fn sample_f32(&self, _: f32, _: f32, _: f32) -> f32 { self.val.luminance() } fn sample_color(&self, _: f32, _: f32, _: f32) -> Colorf { self.val ...
random_line_split
mod.rs
//! Defines the trait implemented by all textured values use std::ops::{Add, Mul}; use film::Colorf; pub use self::image::Image; pub use self::animated_image::AnimatedImage; pub mod image; pub mod animated_image; /// scalars or Colors can be computed on some image texture /// or procedural generator pub trait Text...
<T, F>(x: f32, y: f32, get: F) -> T where T: Copy + Add<T, Output=T> + Mul<f32, Output=T>, F: Fn(u32, u32) -> T { let p00 = (x as u32, y as u32); let p10 = (p00.0 + 1, p00.1); let p01 = (p00.0, p00.1 + 1); let p11 = (p00.0 + 1, p00.1 + 1); let s00 = get(p00.0, p00.1); let s10 = ge...
bilinear_interpolate
identifier_name
mod.rs
//! Defines the trait implemented by all textured values use std::ops::{Add, Mul}; use film::Colorf; pub use self::image::Image; pub use self::animated_image::AnimatedImage; pub mod image; pub mod animated_image; /// scalars or Colors can be computed on some image texture /// or procedural generator pub trait Text...
} pub struct UVColor; impl Texture for UVColor { fn sample_f32(&self, u: f32, v: f32, _: f32) -> f32 { Colorf::new(u, v, 0.0).luminance() } fn sample_color(&self, u: f32, v: f32, _: f32) -> Colorf { Colorf::new(u, v, 0.0) } }
{ self.val }
identifier_body
packet.rs
use std::io; use byteorder::{ReadBytesExt, WriteBytesExt}; use protocol::raknet::packet::Packet; use protocol::raknet::types; use protocol::raknet::{NetworkSerializable, NetworkDeserializable, NetworkSize}; macro_rules! define_mcpe_packets { ($(($id:expr, $name:ident) => {$($field_name:ident: $field_type:ty),*}),+...
} impl Into<PacketTypes> for $name { fn into(self) -> PacketTypes { PacketTypes::$name(self) } } )+ ) } define_mcpe_packets!( (0x01, Login) => { protocol: u32, edition: u8 } );
fn packet_id(&self) -> u8 { $id as u8 }
random_line_split
namespaced-enum-emulate-flat.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 ...
A | B(_) | C {.. } => {} } } mod nest { pub use self::Bar::*; pub enum Bar { D, E(int), F { a: int }, } impl Bar { pub fn foo() {} } } fn _f2(f: Bar) { match f { D | E(_) | F {.. } => {} } } fn main() {}
fn _f(f: Foo) { match f {
random_line_split
namespaced-enum-emulate-flat.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() {}
{}
conditional_block
namespaced-enum-emulate-flat.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 ...
{ D, E(int), F { a: int }, } impl Bar { pub fn foo() {} } } fn _f2(f: Bar) { match f { D | E(_) | F {.. } => {} } } fn main() {}
Bar
identifier_name
request.rs
//! Types for the [`m.key.verification.request`] event. //! //! [`m.key.verification.request`]: https://spec.matrix.org/v1.2/client-server-api/#mkeyverificationrequest use ruma_macros::EventContent; use serde::{Deserialize, Serialize}; use super::VerificationMethod; use crate::{DeviceId, MilliSecondsSinceUnixEpoch, T...
}
{ Self { from_device, transaction_id, methods, timestamp } }
identifier_body
request.rs
//! Types for the [`m.key.verification.request`] event. //! //! [`m.key.verification.request`]: https://spec.matrix.org/v1.2/client-server-api/#mkeyverificationrequest use ruma_macros::EventContent; use serde::{Deserialize, Serialize}; use super::VerificationMethod; use crate::{DeviceId, MilliSecondsSinceUnixEpoch, T...
/// An opaque identifier for the verification request. /// /// Must be unique with respect to the devices involved. pub transaction_id: Box<TransactionId>, /// The verification methods supported by the sender. pub methods: Vec<VerificationMethod>, /// The time in milliseconds for when the ...
random_line_split
request.rs
//! Types for the [`m.key.verification.request`] event. //! //! [`m.key.verification.request`]: https://spec.matrix.org/v1.2/client-server-api/#mkeyverificationrequest use ruma_macros::EventContent; use serde::{Deserialize, Serialize}; use super::VerificationMethod; use crate::{DeviceId, MilliSecondsSinceUnixEpoch, T...
( from_device: Box<DeviceId>, transaction_id: Box<TransactionId>, methods: Vec<VerificationMethod>, timestamp: MilliSecondsSinceUnixEpoch, ) -> Self { Self { from_device, transaction_id, methods, timestamp } } }
new
identifier_name
formdata.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::FormDataBinding; use dom::bindings::cod...
BlobOrUSVString::USVString(s) => FormDatum::StringData(s.0), BlobOrUSVString::Blob(b) => FormDatum::BlobData(JS::from_rooted(&b)) }; self.data.borrow_mut().insert(Atom::from(name.0), vec!(val)); } } impl FormData { fn get_file_or_blob(&self, value: &Blob, filename: Opti...
random_line_split
formdata.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::FormDataBinding; use dom::bindings::cod...
(&self, name: USVString) { self.data.borrow_mut().remove(&Atom::from(name.0)); } // https://xhr.spec.whatwg.org/#dom-formdata-get fn Get(&self, name: USVString) -> Option<BlobOrUSVString> { self.data.borrow() .get(&Atom::from(name.0)) .map(|entry| match entry...
Delete
identifier_name
formdata.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::FormDataBinding; use dom::bindings::cod...
} } // https://xhr.spec.whatwg.org/#dom-formdata-delete fn Delete(&self, name: USVString) { self.data.borrow_mut().remove(&Atom::from(name.0)); } // https://xhr.spec.whatwg.org/#dom-formdata-get fn Get(&self, name: USVString) -> Option<BlobOrUSVString> { self.data.borr...
{ entry.insert(vec!(blob)); }
conditional_block
util.rs
use crate::types::*; use ethereum_types::H256; use hmac::{Hmac, Mac, NewMac}; use secp256k1::PublicKey; use sha2::Sha256; use sha3::{Digest, Keccak256}; use std::fmt::{self, Formatter}; pub fn keccak256(data: &[u8]) -> H256 { H256::from(Keccak256::digest(data).as_ref()) } pub fn sha256(data: &[u8]) -> H256 { ...
let pubkey = PublicKey::from_secret_key(SECP256K1, &prikey); assert_eq!(pubkey, id2pk(pk2id(&pubkey)).unwrap()); } }
#[test] fn pk2id2pk() { let prikey = SecretKey::new(&mut secp256k1::rand::thread_rng());
random_line_split
util.rs
use crate::types::*; use ethereum_types::H256; use hmac::{Hmac, Mac, NewMac}; use secp256k1::PublicKey; use sha2::Sha256; use sha3::{Digest, Keccak256}; use std::fmt::{self, Formatter}; pub fn keccak256(data: &[u8]) -> H256 { H256::from(Keccak256::digest(data).as_ref()) } pub fn sha256(data: &[u8]) -> H256 { ...
pub fn hex_debug<T: AsRef<[u8]>>(s: &T, f: &mut Formatter) -> fmt::Result { f.write_str(&hex::encode(&s)) } #[cfg(test)] mod tests { use super::*; use secp256k1::{SecretKey, SECP256K1}; #[test] fn pk2id2pk() { let prikey = SecretKey::new(&mut secp256k1::rand::thread_rng()); let p...
{ let mut s = [0_u8; 65]; s[0] = 4; s[1..].copy_from_slice(&id.as_bytes()); PublicKey::from_slice(&s) }
identifier_body
util.rs
use crate::types::*; use ethereum_types::H256; use hmac::{Hmac, Mac, NewMac}; use secp256k1::PublicKey; use sha2::Sha256; use sha3::{Digest, Keccak256}; use std::fmt::{self, Formatter}; pub fn keccak256(data: &[u8]) -> H256 { H256::from(Keccak256::digest(data).as_ref()) } pub fn sha256(data: &[u8]) -> H256 { ...
(pk: &PublicKey) -> PeerId { PeerId::from_slice(&pk.serialize_uncompressed()[1..]) } pub fn id2pk(id: PeerId) -> Result<PublicKey, secp256k1::Error> { let mut s = [0_u8; 65]; s[0] = 4; s[1..].copy_from_slice(&id.as_bytes()); PublicKey::from_slice(&s) } pub fn hex_debug<T: AsRef<[u8]>>(s: &T, f: &m...
pk2id
identifier_name
no_0097_interleaving_string.rs
struct Solution; impl Solution { // 题解中没有使用滚动数组优化的动态规划解法。 pub fn is_interleave(s1: String, s2: String, s3: String) -> bool { let (s1, s2, s3) = (s1.as_bytes(), s2.as_bytes(), s3.as_bytes()); let (m, n) = (s1.len(), s2.len()); if m + n!= s3.len() { return false; } ...
#[test] fn test_is_interleave1() { assert_eq!( Solution::is_interleave( "aabcc".to_owned(), "dbbca".to_owned(), "aadbbcbcac".to_owned(), ), true ); } #[test] fn test_is_interleave2() { assert...
mod tests { use super::*;
random_line_split
no_0097_interleaving_string.rs
struct Solution; impl Solution { // 题解中没有使用滚动数组优化的动态规划解法。 pub fn is_interleave(s1: String, s2: String, s3: String) -> bool { let (s1, s2, s3) = (s1.as_bytes(), s2.as_bytes(), s3.as_bytes()); let (m, n) = (s1.len(), s2.len()); if m + n!= s3.len() { return false; } ...
fn test_is_interleave1() { assert_eq!( Solution::is_interleave( "aabcc".to_owned(), "dbbca".to_owned(), "aadbbcbcac".to_owned(), ), true ); } #[test] fn test_is_interleave2() { assert_eq!( ...
i + 1, s2, j, s3, k + 1) { return true; } if j < s2.len() && s3[k] == s2[j] && Self::is_interleave1_helper(s1, i, s2, j + 1, s3, k + 1) { return true; } false } } #[cfg(test)] mod tests { use super::*; #[test...
identifier_body
no_0097_interleaving_string.rs
struct Solution; impl Solution { // 题解中没有使用滚动数组优化的动态规划解法。 pub fn is_interleave(s1: String, s2: String, s3: String) -> bool { let (s1, s2, s3) = (s1.as_bytes(), s2.as_bytes(), s3.as_bytes()); let (m, n) = (s1.len(), s2.len()); if m + n!= s3.len() { return false; } ...
: &[u8], k: usize, ) -> bool { // 都到达终点了,匹配 if k == s3.len() { return i == s1.len() && j == s2.len(); } if i < s1.len() && s3[k] == s1[i] && Self::is_interleave1_helper(s1, i + 1, s2, j, s3, k + 1) { return true; ...
: &[u8], j: usize, s3
conditional_block
no_0097_interleaving_string.rs
struct Solution; impl Solution { // 题解中没有使用滚动数组优化的动态规划解法。 pub fn is_interleave(s1: String, s2: String, s3: String) -> bool { let (s1, s2, s3) = (s1.as_bytes(), s2.as_bytes(), s3.as_bytes()); let (m, n) = (s1.len(), s2.len()); if m + n!= s3.len() { return false; } ...
); } }
identifier_name
trait-inheritance-auto-xc-2.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 a = &A { x: 3 }; f(a); }
main
identifier_name
trait-inheritance-auto-xc-2.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
pub fn main() { let a = &A { x: 3 }; f(a); }
{ assert_eq!(a.f(), 10); assert_eq!(a.g(), 20); assert_eq!(a.h(), 30); }
identifier_body
trait-inheritance-auto-xc-2.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...
// aux-build:trait_inheritance_auto_xc_2_aux.rs extern crate "trait_inheritance_auto_xc_2_aux" as aux; // aux defines impls of Foo, Bar and Baz for A use aux::{Foo, Bar, Baz, A}; // We want to extend all Foo, Bar, Bazes to Quuxes pub trait Quux: Foo + Bar + Baz { } impl<T:Foo + Bar + Baz> Quux for T { } fn f<T:Quux...
random_line_split
mod.rs
pub mod v03; pub mod v10; use chrono::{DateTime, TimeZone, Utc}; use serde_json::{json, Value}; pub fn id() -> String { "0001".to_string() } pub fn ty() -> String { "test_event.test_application".to_string() } pub fn source() -> String { "http://localhost/".to_string() } pub fn json_datacontenttype() ->...
} pub fn time() -> DateTime<Utc> { Utc.ymd(2020, 3, 16).and_hms(11, 50, 00) } pub fn string_extension() -> (String, String) { ("string_ex".to_string(), "val".to_string()) } pub fn bool_extension() -> (String, bool) { ("bool_ex".to_string(), true) } pub fn int_extension() -> (String, i64) { ("int_ex"...
pub fn subject() -> String { "cloudevents-sdk".to_string()
random_line_split
mod.rs
pub mod v03; pub mod v10; use chrono::{DateTime, TimeZone, Utc}; use serde_json::{json, Value}; pub fn id() -> String { "0001".to_string() } pub fn ty() -> String { "test_event.test_application".to_string() } pub fn source() -> String { "http://localhost/".to_string() } pub fn json_datacontenttype() ->...
() -> String { "http://localhost/schema".to_string() } pub fn json_data() -> Value { json!({"hello": "world"}) } pub fn json_data_binary() -> Vec<u8> { serde_json::to_vec(&json!({"hello": "world"})).unwrap() } pub fn xml_data() -> String { "<hello>world</hello>".to_string() } pub fn subject() -> Str...
dataschema
identifier_name
mod.rs
pub mod v03; pub mod v10; use chrono::{DateTime, TimeZone, Utc}; use serde_json::{json, Value}; pub fn id() -> String
pub fn ty() -> String { "test_event.test_application".to_string() } pub fn source() -> String { "http://localhost/".to_string() } pub fn json_datacontenttype() -> String { "application/json".to_string() } pub fn xml_datacontenttype() -> String { "application/xml".to_string() } pub fn dataschema() ...
{ "0001".to_string() }
identifier_body
bignum.rs
use openssl::bn::BigNum; use std::ops::Deref; use super::Part; use result::JwtResult; use rustc_serialize::base64::*; pub struct BigNumComponent(pub BigNum); impl Deref for BigNumComponent { type Target = BigNum;
} impl Into<BigNum> for BigNumComponent { fn into(self) -> BigNum { self.0 } } impl Part for BigNumComponent { type Encoded = String; fn to_base64(&self) -> JwtResult<String> { Ok(ToBase64::to_base64(&self.to_vec()[..], URL_SAFE)) } fn from_base64<B: AsRef<[u8]>>(...
fn deref(&self) -> &Self::Target { &self.0 }
random_line_split
bignum.rs
use openssl::bn::BigNum; use std::ops::Deref; use super::Part; use result::JwtResult; use rustc_serialize::base64::*; pub struct BigNumComponent(pub BigNum); impl Deref for BigNumComponent { type Target = BigNum; fn deref(&self) -> &Self::Target { &self.0 } } impl Into<BigNum> for BigNumComp...
} #[cfg(test)] mod test { use super::*; use Part; #[test] fn test_bignum_base64() { let bn_b64 = "AQAB"; let bn = BigNumComponent::from_base64(bn_b64.as_bytes()).unwrap(); let result = bn.to_base64().unwrap(); assert_eq!(result, bn_b64); } }
{ let decoded = try!(encoded.as_ref().from_base64()); let bn = try!(BigNum::from_slice(&decoded)); Ok(BigNumComponent(bn)) }
identifier_body
bignum.rs
use openssl::bn::BigNum; use std::ops::Deref; use super::Part; use result::JwtResult; use rustc_serialize::base64::*; pub struct BigNumComponent(pub BigNum); impl Deref for BigNumComponent { type Target = BigNum; fn deref(&self) -> &Self::Target { &self.0 } } impl Into<BigNum> for BigNumComp...
<B: AsRef<[u8]>>(encoded: B) -> JwtResult<BigNumComponent> { let decoded = try!(encoded.as_ref().from_base64()); let bn = try!(BigNum::from_slice(&decoded)); Ok(BigNumComponent(bn)) } } #[cfg(test)] mod test { use super::*; use Part; #[test] fn test_bignum_base64() { ...
from_base64
identifier_name