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
session.rs
/* Copyright (C) 2018 Open Information Security Foundation * * You can copy, redistribute or modify this Program under the terms of * the GNU General Public License version 2 as published by the Free * Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARR...
() -> SMBTransactionSessionSetup { return SMBTransactionSessionSetup { request_host: None, response_host: None, ntlmssp: None, krb_ticket: None, } } } impl SMBState { pub fn new_sessionsetup_tx(&mut self, hdr: SMBCommonHdr) -> &mut SMBTran...
new
identifier_name
session.rs
/* Copyright (C) 2018 Open Information Security Foundation * * You can copy, redistribute or modify this Program under the terms of * the GNU General Public License version 2 as published by the Free * Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARR...
return SMBTransactionSessionSetup { request_host: None, response_host: None, ntlmssp: None, krb_ticket: None, } } } impl SMBState { pub fn new_sessionsetup_tx(&mut self, hdr: SMBCommonHdr) -> &mut SMBTransaction { let mut tx = ...
} impl SMBTransactionSessionSetup { pub fn new() -> SMBTransactionSessionSetup {
random_line_split
session.rs
/* Copyright (C) 2018 Open Information Security Foundation * * You can copy, redistribute or modify this Program under the terms of * the GNU General Public License version 2 as published by the Free * Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARR...
}
{ for tx in &mut self.transactions { let hit = tx.hdr.compare(&hdr) && match tx.type_data { Some(SMBTransactionTypeData::SESSIONSETUP(_)) => { true }, _ => { false }, }; if hit { return Some(tx); } } ...
identifier_body
bench_serialization.rs
// Copyright 2017 TiKV Project Authors. Licensed under Apache-2.0. use kvproto::raft_cmdpb::{CmdType, RaftCmdRequest, Request}; use raft::eraftpb::Entry; use protobuf::{self, Message}; use rand::{thread_rng, RngCore}; use test::Bencher; use collections::HashMap; #[inline] fn gen_rand_str(len: usize) -> Vec<u8> { ...
b.iter(|| { encode(&map); }); } #[bench] fn bench_decode_two(b: &mut Bencher) { let key_for_lock = gen_rand_str(30); let value_for_lock = gen_rand_str(10); let key_for_data = gen_rand_str(30); let value_for_data = gen_rand_str(256); let mut map: HashMap<&[u8], &[u8]> = HashMap::defa...
map.insert(&key_for_data, &value_for_data);
random_line_split
bench_serialization.rs
// Copyright 2017 TiKV Project Authors. Licensed under Apache-2.0. use kvproto::raft_cmdpb::{CmdType, RaftCmdRequest, Request}; use raft::eraftpb::Entry; use protobuf::{self, Message}; use rand::{thread_rng, RngCore}; use test::Bencher; use collections::HashMap; #[inline] fn gen_rand_str(len: usize) -> Vec<u8> { ...
#[bench] fn bench_decode_one(b: &mut Bencher) { let key = gen_rand_str(30); let value = gen_rand_str(256); let mut map: HashMap<&[u8], &[u8]> = HashMap::default(); map.insert(&key, &value); let data = encode(&map); b.iter(|| { decode(&data); }); } #[bench] fn bench_encode_two(b: &...
{ let key = gen_rand_str(30); let value = gen_rand_str(256); let mut map: HashMap<&[u8], &[u8]> = HashMap::default(); map.insert(&key, &value); b.iter(|| { encode(&map); }); }
identifier_body
bench_serialization.rs
// Copyright 2017 TiKV Project Authors. Licensed under Apache-2.0. use kvproto::raft_cmdpb::{CmdType, RaftCmdRequest, Request}; use raft::eraftpb::Entry; use protobuf::{self, Message}; use rand::{thread_rng, RngCore}; use test::Bencher; use collections::HashMap; #[inline] fn gen_rand_str(len: usize) -> Vec<u8> { ...
(b: &mut Bencher) { let key_for_lock = gen_rand_str(30); let value_for_lock = gen_rand_str(10); let key_for_data = gen_rand_str(30); let value_for_data = gen_rand_str(256); let mut map: HashMap<&[u8], &[u8]> = HashMap::default(); map.insert(&key_for_lock, &value_for_lock); map.insert(&key_fo...
bench_decode_two
identifier_name
main.rs
extern crate rand; use std::io; use std::cmp::Ordering; use rand::Rng; fn
() { println!("Guess the number!"); let secret_number = rand::thread_rng().gen_range(1, 101); println!("The secret number is {}", secret_number); loop { println!("Please input your guess."); let mut guess = String::new(); io::stdin().read_line(&mut guess) .expect(...
main
identifier_name
main.rs
extern crate rand; use std::io; use std::cmp::Ordering; use rand::Rng; fn main()
println!("You guessed: {}", guess); match guess.cmp(&secret_number) { // Ordering は enum Ordering::Less => println!("Too small!"), Ordering::Greater => println!("Too big!"), Ordering::Equal => { println!("You win!"); ...
{ println!("Guess the number!"); let secret_number = rand::thread_rng().gen_range(1, 101); println!("The secret number is {}", secret_number); loop { println!("Please input your guess."); let mut guess = String::new(); io::stdin().read_line(&mut guess) .expect("F...
identifier_body
main.rs
extern crate rand; use std::io; use std::cmp::Ordering; use rand::Rng; fn main() { println!("Guess the number!"); let secret_number = rand::thread_rng().gen_range(1, 101); println!("The secret number is {}", secret_number); loop { println!("Please input your guess."); let mut guess...
conditional_block
main.rs
extern crate rand; use std::io; use std::cmp::Ordering; use rand::Rng; fn main() { println!("Guess the number!"); let secret_number = rand::thread_rng().gen_range(1, 101); println!("The secret number is {}", secret_number); loop { println!("Please input your guess."); let mut guess...
break; } } } }
Ordering::Greater => println!("Too big!"), Ordering::Equal => { println!("You win!");
random_line_split
event.rs
use devices::{HatSwitch, JoystickState}; /// State of a Key or Button #[derive(Eq, PartialEq, Clone, Debug)] pub enum State { Pressed, Released, } /// Key Identifier (UK Keyboard Layout) #[derive(Eq, PartialEq, Hash, Clone, Debug)] pub enum KeyId { Escape, Return, Backspace, Lef...
if let Some(value_self) = self.hatswitch.clone() { if value_self!= value_other { output.push(RawEvent::JoystickHatSwitchEvent(id, value_other)); } } } output } }
if let Some(value_other) = other_state.hatswitch {
random_line_split
event.rs
use devices::{HatSwitch, JoystickState}; /// State of a Key or Button #[derive(Eq, PartialEq, Clone, Debug)] pub enum State { Pressed, Released, } /// Key Identifier (UK Keyboard Layout) #[derive(Eq, PartialEq, Hash, Clone, Debug)] pub enum KeyId { Escape, Return, Backspace, Lef...
} if let Some(value_other) = other_state.hatswitch { if let Some(value_self) = self.hatswitch.clone() { if value_self!= value_other { output.push(RawEvent::JoystickHatSwitchEvent(id, value_other)); } } } ...
{ output.push(RawEvent::JoystickAxisEvent(id, Axis::SLIDER, value)); }
conditional_block
event.rs
use devices::{HatSwitch, JoystickState}; /// State of a Key or Button #[derive(Eq, PartialEq, Clone, Debug)] pub enum
{ Pressed, Released, } /// Key Identifier (UK Keyboard Layout) #[derive(Eq, PartialEq, Hash, Clone, Debug)] pub enum KeyId { Escape, Return, Backspace, Left, Right, Up, Down, Space, A, B, C, D, E, F, G, H, I, J, ...
State
identifier_name
client.rs
extern crate nanomsg; use std::thread; use std::time::Duration; use std::sync::mpsc::*; use super::media_player; use super::protocol; use self::nanomsg::{Socket, Protocol, Error}; pub fn run(rx_quit: Receiver<bool>, tx_state: Sender<media_player::State>)
if let Err(_) = tx_state.send(state) { break; } }, Err(Error::TryAgain) => {}, Err(err) => panic!("Problem receiving msg: {}", err), } thread::sleep(...
{ let mut subscriber = match Socket::new(Protocol::Sub) { Ok(socket) => socket, Err(err) => panic!("{}", err) }; subscriber.subscribe(&String::from("").into_bytes()[..]); subscriber.set_receive_timeout(500).unwrap(); match subscriber.connect("tcp://*:5555") { Ok(_) => println!("Connected to se...
identifier_body
client.rs
extern crate nanomsg; use std::thread; use std::time::Duration; use std::sync::mpsc::*; use super::media_player; use super::protocol; use self::nanomsg::{Socket, Protocol, Error}; pub fn
(rx_quit: Receiver<bool>, tx_state: Sender<media_player::State>) { let mut subscriber = match Socket::new(Protocol::Sub) { Ok(socket) => socket, Err(err) => panic!("{}", err) }; subscriber.subscribe(&String::from("").into_bytes()[..]); subscriber.set_receive_timeout(500).unwrap(); match subscriber...
run
identifier_name
client.rs
extern crate nanomsg; use std::thread; use std::time::Duration; use std::sync::mpsc::*; use super::media_player; use super::protocol;
pub fn run(rx_quit: Receiver<bool>, tx_state: Sender<media_player::State>) { let mut subscriber = match Socket::new(Protocol::Sub) { Ok(socket) => socket, Err(err) => panic!("{}", err) }; subscriber.subscribe(&String::from("").into_bytes()[..]); subscriber.set_receive_timeout(500).unwrap(); matc...
use self::nanomsg::{Socket, Protocol, Error};
random_line_split
route_guard.rs
#![feature(plugin, custom_derive)] #![plugin(rocket_codegen)] extern crate rocket; use std::path::PathBuf; use rocket::Route; #[get("/<path..>")] fn files(route: &Route, path: PathBuf) -> String { format!("{}/{}", route.base(), path.to_string_lossy()) } mod route_guard_tests { use super::*; use rocket::...
}
{ let rocket = rocket::ignite() .mount("/first", routes![files]) .mount("/second", routes![files]); let client = Client::new(rocket).unwrap(); assert_path(&client, "/first/some/path"); assert_path(&client, "/second/some/path"); assert_path(&client, "/firs...
identifier_body
route_guard.rs
#![feature(plugin, custom_derive)] #![plugin(rocket_codegen)] extern crate rocket; use std::path::PathBuf; use rocket::Route;
fn files(route: &Route, path: PathBuf) -> String { format!("{}/{}", route.base(), path.to_string_lossy()) } mod route_guard_tests { use super::*; use rocket::local::Client; fn assert_path(client: &Client, path: &str) { let mut res = client.get(path).dispatch(); assert_eq!(res.body_stri...
#[get("/<path..>")]
random_line_split
route_guard.rs
#![feature(plugin, custom_derive)] #![plugin(rocket_codegen)] extern crate rocket; use std::path::PathBuf; use rocket::Route; #[get("/<path..>")] fn files(route: &Route, path: PathBuf) -> String { format!("{}/{}", route.base(), path.to_string_lossy()) } mod route_guard_tests { use super::*; use rocket::...
(client: &Client, path: &str) { let mut res = client.get(path).dispatch(); assert_eq!(res.body_string(), Some(path.into())); } #[test] fn check_mount_path() { let rocket = rocket::ignite() .mount("/first", routes![files]) .mount("/second", routes![files]); ...
assert_path
identifier_name
rcvr-borrowed-to-region.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_eq!(y, 6); let x = @6; let y = x.get(); info2!("y={}", y); assert_eq!(y, 6); let x = ~6; let y = x.get(); info2!("y={}", y); assert_eq!(y, 6); let x = &6; let y = x.get(); info2!("y={}", y); assert_eq!(y, 6); }
pub fn main() { let x = @mut 6; let y = x.get();
random_line_split
rcvr-borrowed-to-region.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
{ let x = @mut 6; let y = x.get(); assert_eq!(y, 6); let x = @6; let y = x.get(); info2!("y={}", y); assert_eq!(y, 6); let x = ~6; let y = x.get(); info2!("y={}", y); assert_eq!(y, 6); let x = &6; let y = x.get(); info2!("y={}", y); assert_eq!(y, 6); }
identifier_body
rcvr-borrowed-to-region.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 ...
(self) -> int { return *self; } } pub fn main() { let x = @mut 6; let y = x.get(); assert_eq!(y, 6); let x = @6; let y = x.get(); info2!("y={}", y); assert_eq!(y, 6); let x = ~6; let y = x.get(); info2!("y={}", y); assert_eq!(y, 6); let x = &6; let y =...
get
identifier_name
ast.rs
use std::fmt; use std::from_str::FromStr; use operators::{Operator, Sub, Skip, Loop}; /** The internal parsed representation of a program source. */ pub struct Ast(~[Operator]); impl Ast { /** Produce an AST from a source string. This is the most commod method to generate an Ast. */ pub fn parse_str(source: &st...
) } }
fn fmt(&self, f:&mut fmt::Formatter) -> fmt::Result { let &Ast(ref ops) = self; let display = |op: &Operator| -> ~str { format!("{}", op) }; let repr: ~[~str] = ops.iter().map(display).collect(); f.buf.write(format!("{}", repr.concat()).as_bytes()
random_line_split
ast.rs
use std::fmt; use std::from_str::FromStr; use operators::{Operator, Sub, Skip, Loop}; /** The internal parsed representation of a program source. */ pub struct Ast(~[Operator]); impl Ast { /** Produce an AST from a source string. This is the most commod method to generate an Ast. */ pub fn parse_str(source: &st...
ops = ~[]; } /* End of a loop. Make a subprocess operator out of the just-collected context, and push that on the previous context. */ Some(Loop) => { let sub_ast = Sub(Ast( ops )); // Try to pop the previous context from the stack. // If this does not work, it's an unmat...
{ /* We parse loops by making a context to group its operators, pushing on it until the matching loop end. As we create the context, we push the previous one onto a stack. After the nest has been collected, we pop the context and replace it with the subprocess operator. */ let mut stack:~[ ~[Operator] ]...
identifier_body
ast.rs
use std::fmt; use std::from_str::FromStr; use operators::{Operator, Sub, Skip, Loop}; /** The internal parsed representation of a program source. */ pub struct
(~[Operator]); impl Ast { /** Produce an AST from a source string. This is the most commod method to generate an Ast. */ pub fn parse_str(source: &str) -> Result<Ast, ~str> { /* We parse loops by making a context to group its operators, pushing on it until the matching loop end. As we create the context, ...
Ast
identifier_name
scale.rs
/// Enum that describes how the /// transcription from a value to a color is done. pub enum Scale { /// Linearly translate a value range to a color range Linear { min: f32, max: f32}, /// Log (ish) translation from a value range to a color range Log { min: f32, max: f32}, /// Exponantial (ish) trans...
(scale: &Scale, value: f32) -> f32 { match scale { &Scale::Linear{min, max} => { if value < min { 0. } else if value > max { 1. } else { (value - min) / (max - min) } }, &Scale::Log{min, max} => {...
normalize
identifier_name
scale.rs
/// Enum that describes how the /// transcription from a value to a color is done. pub enum Scale { /// Linearly translate a value range to a color range Linear { min: f32, max: f32}, /// Log (ish) translation from a value range to a color range Log { min: f32, max: f32}, /// Exponantial (ish) trans...
, } }
{ value }
conditional_block
scale.rs
/// Enum that describes how the /// transcription from a value to a color is done. pub enum Scale { /// Linearly translate a value range to a color range Linear { min: f32, max: f32}, /// Log (ish) translation from a value range to a color range Log { min: f32, max: f32}, /// Exponantial (ish) trans...
} }
}, &Scale::Equal => { value },
random_line_split
fs.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
// times are in milliseconds (currently) fn mktime(&self, secs: u64, nsecs: u64) -> u64 { secs * 1000 + nsecs / 1000000 } } impl AsInner<raw::stat> for FileAttr { fn as_inner(&self) -> &raw::stat { &self.stat } } #[unstable(feature = "metadata_ext", reason = "recently added API")] pub trait ...
{ &self.stat }
identifier_body
fs.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
(&mut self, create: bool) { self.flag(libc::O_CREAT, create); } pub fn mode(&mut self, mode: raw::mode_t) { self.mode = mode as mode_t; } fn flag(&mut self, bit: c_int, on: bool) { if on { self.flags |= bit; } else { self.flags &=!bit; } ...
create
identifier_name
fs.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
let entry = DirEntry { buf: buf, root: self.root.clone() }; if entry.name_bytes() == b"." || entry.name_bytes() == b".." { buf = entry.buf; } else { return Some(Ok(entry)) } } } } i...
{ return None }
conditional_block
fs.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
pub fn path(&self) -> PathBuf { self.root.join(<OsStr as OsStrExt>::from_bytes(self.name_bytes())) } pub fn file_name(&self) -> OsString { OsStr::from_bytes(self.name_bytes()).to_os_string() } pub fn metadata(&self) -> io::Result<FileAttr> { lstat(&self.path()) } p...
} } impl DirEntry {
random_line_split
mod.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
match action(addr) { Ok(r) => return Ok(r), Err(e) => err = e } } Err(err) }
for addr in addresses.into_iter() {
random_line_split
translation_construction.rs
#[cfg(feature = "arbitrary")] use crate::base::storage::Owned; #[cfg(feature = "arbitrary")] use quickcheck::{Arbitrary, Gen}; use num::{One, Zero}; use rand::distributions::{Distribution, Standard}; use rand::Rng; use simba::scalar::ClosedAdd; use crate::base::allocator::Allocator; use crate::base::dimension::{DimN...
<'a, G: Rng +?Sized>(&self, rng: &'a mut G) -> Translation<N, D> { Translation::from(rng.gen::<VectorN<N, D>>()) } } #[cfg(feature = "arbitrary")] impl<N: Scalar + Arbitrary, D: DimName> Arbitrary for Translation<N, D> where DefaultAllocator: Allocator<N, D>, Owned<N, D>: Send, { #[inline] ...
sample
identifier_name
translation_construction.rs
#[cfg(feature = "arbitrary")] use crate::base::storage::Owned; #[cfg(feature = "arbitrary")]
use simba::scalar::ClosedAdd; use crate::base::allocator::Allocator; use crate::base::dimension::{DimName, U1, U2, U3, U4, U5, U6}; use crate::base::{DefaultAllocator, Scalar, VectorN}; use crate::geometry::Translation; impl<N: Scalar + Zero, D: DimName> Translation<N, D> where DefaultAllocator: Allocator<N, D>...
use quickcheck::{Arbitrary, Gen}; use num::{One, Zero}; use rand::distributions::{Distribution, Standard}; use rand::Rng;
random_line_split
translation_construction.rs
#[cfg(feature = "arbitrary")] use crate::base::storage::Owned; #[cfg(feature = "arbitrary")] use quickcheck::{Arbitrary, Gen}; use num::{One, Zero}; use rand::distributions::{Distribution, Standard}; use rand::Rng; use simba::scalar::ClosedAdd; use crate::base::allocator::Allocator; use crate::base::dimension::{DimN...
} impl<N: Scalar, D: DimName> Distribution<Translation<N, D>> for Standard where DefaultAllocator: Allocator<N, D>, Standard: Distribution<N>, { #[inline] fn sample<'a, G: Rng +?Sized>(&self, rng: &'a mut G) -> Translation<N, D> { Translation::from(rng.gen::<VectorN<N, D>>()) } } #[cfg(fe...
{ Self::identity() }
identifier_body
stream.rs
// Copyright © 2017-2018 Mozilla Foundation // // This program is made available under an ISC-style license. See the // accompanying file LICENSE for details. use callbacks::cubeb_device_changed_callback; use channel::cubeb_channel_layout; use device::cubeb_device; use format::cubeb_sample_format; use std::{fmt, mem}...
{} #[repr(C)] #[derive(Clone, Copy)] pub struct cubeb_stream_params { pub format: cubeb_sample_format, pub rate: c_uint, pub channels: c_uint, pub layout: cubeb_channel_layout, pub prefs: cubeb_stream_prefs, } impl Default for cubeb_stream_params { fn default() -> Self { unsafe { mem::...
ubeb_stream
identifier_name
stream.rs
// Copyright © 2017-2018 Mozilla Foundation // // This program is made available under an ISC-style license. See the // accompanying file LICENSE for details. use callbacks::cubeb_device_changed_callback; use channel::cubeb_channel_layout; use device::cubeb_device; use format::cubeb_sample_format; use std::{fmt, mem}...
CUBEB_STREAM_PREF_NONE = 0x00, CUBEB_STREAM_PREF_LOOPBACK = 0x01, CUBEB_STREAM_PREF_DISABLE_DEVICE_SWITCHING = 0x02, CUBEB_STREAM_PREF_VOICE = 0x04, } } cubeb_enum! { pub enum cubeb_state { CUBEB_STATE_STARTED, CUBEB_STATE_STOPPED, CUBEB_STATE_DRAINED, ...
random_line_split
build.rs
extern crate bindgen; use std::fs::{File, create_dir_all, metadata}; use std::path::Path; use std::io::{ErrorKind, Write}; const HEADERS : &'static [&'static str] = &["ssl", "entropy", "ctr_drbg"]; const HEADER_BASE : &'static str = "/usr/local/include/mbedtls/"; const MOD_FILE : &'static str = r#" #[allow(dead_co...
} }
{ let mut mod_file = File::create(mod_file_str).unwrap(); mod_file.write(MOD_FILE.as_bytes()).unwrap(); }
conditional_block
build.rs
extern crate bindgen; use std::fs::{File, create_dir_all, metadata};
use std::io::{ErrorKind, Write}; const HEADERS : &'static [&'static str] = &["ssl", "entropy", "ctr_drbg"]; const HEADER_BASE : &'static str = "/usr/local/include/mbedtls/"; const MOD_FILE : &'static str = r#" #[allow(dead_code, non_camel_case_types, non_snake_case, non_upper_case_globals)] mod bindings; "#; fn ma...
use std::path::Path;
random_line_split
build.rs
extern crate bindgen; use std::fs::{File, create_dir_all, metadata}; use std::path::Path; use std::io::{ErrorKind, Write}; const HEADERS : &'static [&'static str] = &["ssl", "entropy", "ctr_drbg"]; const HEADER_BASE : &'static str = "/usr/local/include/mbedtls/"; const MOD_FILE : &'static str = r#" #[allow(dead_co...
fn gen(header: &str) { let dir = "src/mbed/".to_string() + header + "/"; let file = dir.clone() + "bindings.rs"; create_dir_all(&dir).unwrap(); let bindings_file = File::create(file).unwrap(); bindgen::Builder::default() .header(HEADER_BASE.to_string() + header + ".h") .link("mbed...
{ for header in HEADERS.iter() { gen(header); } }
identifier_body
build.rs
extern crate bindgen; use std::fs::{File, create_dir_all, metadata}; use std::path::Path; use std::io::{ErrorKind, Write}; const HEADERS : &'static [&'static str] = &["ssl", "entropy", "ctr_drbg"]; const HEADER_BASE : &'static str = "/usr/local/include/mbedtls/"; const MOD_FILE : &'static str = r#" #[allow(dead_co...
() { for header in HEADERS.iter() { gen(header); } } fn gen(header: &str) { let dir = "src/mbed/".to_string() + header + "/"; let file = dir.clone() + "bindings.rs"; create_dir_all(&dir).unwrap(); let bindings_file = File::create(file).unwrap(); bindgen::Builder::default() ...
main
identifier_name
generate.rs
//! Generate valid parse trees. use grammar::repr::*; use rand::{self, Rng}; use std::iter::Iterator; #[derive(PartialEq, Eq)] pub enum ParseTree { Nonterminal(NonterminalString, Vec<ParseTree>), Terminal(TerminalString), } pub fn random_parse_tree(grammar: &Grammar, symbol: NonterminalString) -> ParseTree {
let mut gen = Generator { grammar: grammar, rng: rand::thread_rng(), depth: 0, }; loop { // sometimes, the random walk overflows the stack, so we have a max, and if // it is exceeded, we just try again if let Some(result) = gen.nonterminal(symbol.clone()) { ...
random_line_split
generate.rs
//! Generate valid parse trees. use grammar::repr::*; use rand::{self, Rng}; use std::iter::Iterator; #[derive(PartialEq, Eq)] pub enum ParseTree { Nonterminal(NonterminalString, Vec<ParseTree>), Terminal(TerminalString), } pub fn random_parse_tree(grammar: &Grammar, symbol: NonterminalString) -> ParseTree
struct Generator<'grammar> { grammar: &'grammar Grammar, rng: rand::rngs::ThreadRng, depth: u32, } const MAX_DEPTH: u32 = 10000; impl<'grammar> Generator<'grammar> { fn nonterminal(&mut self, nt: NonterminalString) -> Option<ParseTree> { if self.depth > MAX_DEPTH { return None; ...
{ let mut gen = Generator { grammar: grammar, rng: rand::thread_rng(), depth: 0, }; loop { // sometimes, the random walk overflows the stack, so we have a max, and if // it is exceeded, we just try again if let Some(result) = gen.nonterminal(symbol.clone()) { ...
identifier_body
generate.rs
//! Generate valid parse trees. use grammar::repr::*; use rand::{self, Rng}; use std::iter::Iterator; #[derive(PartialEq, Eq)] pub enum
{ Nonterminal(NonterminalString, Vec<ParseTree>), Terminal(TerminalString), } pub fn random_parse_tree(grammar: &Grammar, symbol: NonterminalString) -> ParseTree { let mut gen = Generator { grammar: grammar, rng: rand::thread_rng(), depth: 0, }; loop { // sometimes,...
ParseTree
identifier_name
udp_connection.rs
/* * Copyright (C) 2017 Genymobile * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed ...
let rc2 = rc.clone(); // must anotate selector type: https://stackoverflow.com/a/44004103/1987178 let handler = move |selector: &mut Selector, event| rc2.borrow_mut().on_ready(selector, event); let token = selector.register( &self_ref.socke...
{ cx_info!(target: TAG, id, "Open"); let socket = Self::create_socket(&id)?; let packetizer = Packetizer::new(&ipv4_header, &transport_header); let interests = Ready::readable(); let rc = Rc::new(RefCell::new(Self { id: id, client: client, sock...
identifier_body
udp_connection.rs
/* * Copyright (C) 2017 Genymobile * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed ...
Err(err) => { cx_warn!( target: TAG, self.id, "Cannot send to network, drop packet: {}", err ) } } } fn close(&mut self, selector: &mut Selector) { cx_info!(ta...
) { Ok(_) => { self.update_interests(selector); }
random_line_split
udp_connection.rs
/* * Copyright (C) 2017 Genymobile * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed ...
(&self) -> bool { self.closed } }
is_closed
identifier_name
pan.rs
use traits::{SoundSample, SampleValue, stereo_value}; use params::*; use super::Efx; // 0. => all right 1. => all left declare_params!(PanParams { pan: 0.5 }); pub struct Pan { params: PanParams, } impl Parametrized for Pan { fn get_parameters(&mut self) -> &mut Parameters { &mut self.params } } ...
}
}
random_line_split
pan.rs
use traits::{SoundSample, SampleValue, stereo_value}; use params::*; use super::Efx; // 0. => all right 1. => all left declare_params!(PanParams { pan: 0.5 }); pub struct
{ params: PanParams, } impl Parametrized for Pan { fn get_parameters(&mut self) -> &mut Parameters { &mut self.params } } impl Pan { pub fn new(params: PanParams) -> Pan { Pan { params: params } } } impl Efx for Pan { fn sample(&mut self, sample: SampleValue) -> SoundSample {...
Pan
identifier_name
pan.rs
use traits::{SoundSample, SampleValue, stereo_value}; use params::*; use super::Efx; // 0. => all right 1. => all left declare_params!(PanParams { pan: 0.5 }); pub struct Pan { params: PanParams, } impl Parametrized for Pan { fn get_parameters(&mut self) -> &mut Parameters { &mut self.params } } ...
} impl Efx for Pan { fn sample(&mut self, sample: SampleValue) -> SoundSample { let right_v = self.params.pan.value(); let left_v = 1. - right_v; match sample { SampleValue::Mono(x) => stereo_value(x * right_v, x * left_v), SampleValue::Stereo(r, l) => stereo_valu...
{ Pan { params: params } }
identifier_body
escapetime.rs
// Copyright (c) 2015-2019 William (B.J.) Snow Orvis // // 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 applicab...
ctx: CanvasRenderingContext2d, etsystem: Box<dyn EscapeTime>, ) -> EscapeTimeAnimation { let view_area_c = etsystem.default_view_area(); let view_area = [ geometry::Point::from(view_area_c[0]), geometry::Point::from(view_area_c[1]), ]; EscapeTi...
impl EscapeTimeAnimation { pub fn new(
random_line_split
escapetime.rs
// Copyright (c) 2015-2019 William (B.J.) Snow Orvis // // 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 applicab...
}) .flatten() .collect::<Vec<&u8>>() }) .flatten() .cloned() .collect::<Vec<u8>>(); // Construct a Clamped Uint8 Array log::debug!("build clamped image array"); let clamped_image_array = Clam...
{ colors[cmp::min(time, 50 - 1) as usize].0.iter() }
conditional_block
escapetime.rs
// Copyright (c) 2015-2019 William (B.J.) Snow Orvis // // 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 applicab...
fn render(&self) { let screen_width = self.ctx.canvas().unwrap().width(); let screen_height = self.ctx.canvas().unwrap().height(); let vat = geometry::ViewAreaTransformer::new( [screen_width.into(), screen_height.into()], self.view_area[0], self.view_are...
{ let view_area_c = etsystem.default_view_area(); let view_area = [ geometry::Point::from(view_area_c[0]), geometry::Point::from(view_area_c[1]), ]; EscapeTimeAnimation { ctx, etsystem, view_area, } }
identifier_body
escapetime.rs
// Copyright (c) 2015-2019 William (B.J.) Snow Orvis // // 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 applicab...
(&mut self, x1: f64, y1: f64, x2: f64, y2: f64) -> bool { let screen_width = self.ctx.canvas().unwrap().width(); let screen_height = self.ctx.canvas().unwrap().height(); // get the vat for the current view area let vat = geometry::ViewAreaTransformer::new( [screen_width.into...
zoom
identifier_name
lib.rs
self.size.unwrap_or(0) } fn code_file(&self) -> Cow<str> { self.code_file .as_ref() .map_or(Cow::from(""), |s| Cow::Borrowed(&s[..])) } fn code_identifier(&self) -> Cow<str> { self.code_identifier .as_ref() .map_or(Cow::from(""), |s| Cow::B...
} impl fmt::Display for SymbolResult { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { SymbolResult::Ok(_) => write!(f, "Ok"), SymbolResult::NotFound => write!(f, "Not found"), SymbolResult::LoadError(ref e) => write!(f, "Load error: {}", e), ...
{ match (self, other) { (&SymbolResult::Ok(ref a), &SymbolResult::Ok(ref b)) => a == b, (&SymbolResult::NotFound, &SymbolResult::NotFound) => true, (&SymbolResult::LoadError(_), &SymbolResult::LoadError(_)) => true, _ => false, } }
identifier_body
lib.rs
self.size.unwrap_or(0) } fn code_file(&self) -> Cow<str> { self.code_file .as_ref() .map_or(Cow::from(""), |s| Cow::Borrowed(&s[..])) } fn code_identifier(&self) -> Cow<str> { self.code_identifier .as_ref() .map_or(Cow::from(""), |s| Cow:...
/// /// [simplemodule]: struct.SimpleModule.html /// [simpleframe]: struct.SimpleFrame.html pub fn fill_symbol(&self, module: &dyn Module, frame: &mut dyn FrameSymbolizer) { let k = key(module); self.ensure_module(module, &k); if let Some(SymbolResult::Ok(ref sym)) = self.symbols...
/// assert_eq!(f.source_file.unwrap(), r"c:\program files\microsoft visual studio 8\vc\include\swprintf.inl"); /// assert_eq!(f.source_line.unwrap(), 51); /// ```
random_line_split
lib.rs
self.size.unwrap_or(0) } fn
(&self) -> Cow<str> { self.code_file .as_ref() .map_or(Cow::from(""), |s| Cow::Borrowed(&s[..])) } fn code_identifier(&self) -> Cow<str> { self.code_identifier .as_ref() .map_or(Cow::from(""), |s| Cow::Borrowed(&s[..])) } fn debug_file(&self) -...
code_file
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, PropertyAnima...
(shared: &SharedStyleContext) -> Self { ThreadLocalStyleContext { style_sharing_candidate_cache: StyleSharingCandidateCache::new(), bloom_filter: StyleBloom::new(), new_animations_sender: shared.local_context_creation_data.lock().unwrap().new_animations_sender.clone(), ...
new
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, PropertyAnima...
/// recalculation can be sent. pub new_animations_sender: Sender<Animation>, /// A set of tasks to be run (on the parent thread) in sequential mode after /// the rest of the styling is complete. This is useful for infrequently-needed /// non-threadsafe operations. pub tasks: Vec<SequentialTask<E...
pub style_sharing_candidate_cache: StyleSharingCandidateCache<E>, /// The bloom filter used to fast-reject selector-matching. pub bloom_filter: StyleBloom<E>, /// A channel on which new animations that have been triggered by style
random_line_split
cartesian_joint.rs
use na::{self, DVectorSliceMut, RealField}; use crate::joint::Joint; use crate::math::{Isometry, JacobianSliceMut, Translation, Vector, Velocity, DIM}; use crate::solver::IntegrationParameters; /// A joint that allows only all the translational degrees of freedom between two multibody links. #[derive(Copy, Clone, De...
(&self, _: &mut DVectorSliceMut<N>) {} fn integrate(&mut self, parameters: &IntegrationParameters<N>, vels: &[N]) { self.position += Vector::from_row_slice(&vels[..DIM]) * parameters.dt(); } fn apply_displacement(&mut self, disp: &[N]) { self.position += Vector::from_row_slice(&disp[..DIM]...
default_damping
identifier_name
cartesian_joint.rs
use na::{self, DVectorSliceMut, RealField}; use crate::joint::Joint; use crate::math::{Isometry, JacobianSliceMut, Translation, Vector, Velocity, DIM}; use crate::solver::IntegrationParameters; /// A joint that allows only all the translational degrees of freedom between two multibody links. #[derive(Copy, Clone, De...
CartesianJoint { position } } } impl<N: RealField> Joint<N> for CartesianJoint<N> { #[inline] fn ndofs(&self) -> usize { DIM } fn body_to_parent(&self, parent_shift: &Vector<N>, body_shift: &Vector<N>) -> Isometry<N> { let t = Translation::from(parent_shift - body_shift + s...
impl<N: RealField> CartesianJoint<N> { /// Create a cartesian joint with an initial position given by `position`. pub fn new(position: Vector<N>) -> Self {
random_line_split
cartesian_joint.rs
use na::{self, DVectorSliceMut, RealField}; use crate::joint::Joint; use crate::math::{Isometry, JacobianSliceMut, Translation, Vector, Velocity, DIM}; use crate::solver::IntegrationParameters; /// A joint that allows only all the translational degrees of freedom between two multibody links. #[derive(Copy, Clone, De...
fn jacobian_dot_veldiff_mul_coordinates( &self, _: &Isometry<N>, _: &[N], _: &mut JacobianSliceMut<N>, ) { } fn jacobian_mul_coordinates(&self, vels: &[N]) -> Velocity<N> { Velocity::from_vectors(Vector::from_row_slice(&vels[..DIM]), na::zero()) } fn j...
{}
identifier_body
cita_protocol.rs
// Copyright Cryptape Technologies LLC. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed ...
pub const HEAD_ADDRESS_OFFSET: usize = 4 + 4 + 8; pub const HEAD_KEY_LEN_OFFSET: usize = 4 + 4 + 8 + 20; pub const HEAD_TTL_OFFSET: usize = 4 + 4 + 8 + 20 + 1; pub const DEFAULT_TTL_NUM: u8 = 0; pub const CONSENSUS_TTL_NUM: u8 = 9; pub const CONSENSUS_STR: &str = "consensus"; #[derive(Debug, Clone)] pub struct NetMes...
pub const HEAD_VERSION_OFFSET: usize = 4 + 4;
random_line_split
cita_protocol.rs
// Copyright Cryptape Technologies LLC. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed ...
} impl Default for NetMessageUnit { fn default() -> Self { NetMessageUnit { key: String::default(), data: Vec::new(), addr: Address::zero(), version: 0, ttl: DEFAULT_TTL_NUM, } } } pub fn pubsub_message_to_network_message(info: &NetM...
{ NetMessageUnit { key, data, addr, version, ttl, } }
identifier_body
cita_protocol.rs
// Copyright Cryptape Technologies LLC. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed ...
(info: &NetMessageUnit) -> Option<Bytes> { let length_key = info.key.len(); // Use 1 byte to store key length. if length_key == 0 || length_key > u8::max_value() as usize { error!( "[CitaProtocol] The MQ message key is too long or empty {}.", info.key ); retur...
pubsub_message_to_network_message
identifier_name
cita_protocol.rs
// Copyright Cryptape Technologies LLC. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed ...
Some(NetMessageUnit { key, data: buf.to_vec(), addr, version, ttl, }) } #[cfg(test)] mod test { use super::{ network_message_to_pubsub_message, pubsub_message_to_network_message, NetMessageUnit, }; use bytes::BytesMut; #[test] fn convert_emp...
{ warn!("[CitaProtocol] Network message is empty."); }
conditional_block
unique-pinned-nocopy-2.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
() { let i = @mut 0; { let j = ~r(i); } assert_eq!(*i, 1); }
main
identifier_name
unique-pinned-nocopy-2.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 ...
fn r(i: @mut int) -> r { r { i: i } } pub fn main() { let i = @mut 0; { let j = ~r(i); } assert_eq!(*i, 1); }
}
random_line_split
unique-pinned-nocopy-2.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 ...
} fn r(i: @mut int) -> r { r { i: i } } pub fn main() { let i = @mut 0; { let j = ~r(i); } assert_eq!(*i, 1); }
{ unsafe { *(self.i) = *(self.i) + 1; } }
identifier_body
type_infer.rs
/* 类型推导引擎不仅仅在初始化期间分析右值的类型, 还会通过分析变量在后面是 怎么使用的来推导该变量的类型 */ fn main() { // 借助类型标注,编译器知道 `elem` 具有 u8 类型 let elem = 5u8; // 创建一个空 vector(可增长数组)。 let m
ut vec = Vec::new(); // 此时编译器并未知道 `vec` 的确切类型,它只知道 `vec` 是一个含有某种类型 // 的 vector(`Vec<_>`)。 // 将 `elem` 插入 vector。 vec.push(elem); // Aha!现在编译器就知道了 `vec` 是一个含有 `u8` 类型的 vector(`Vec<u8>`) // 试一试 ^ 尝试将 `vec.push(elem)` 那行注释掉 println!("{:?}", vec); }
identifier_body
type_infer.rs
/* 类型推导引擎不仅仅在初始化期间分析右值的类型, 还会通过分析变量在后面是 怎么使用的来推导该变量的类型 */ fn main() { // 借助类型标注,编译器知道 `elem` 具有 u8 类型 let elem = 5u8; // 创建一个空 vector(可增长数组)。
t mut vec = Vec::new(); // 此时编译器并未知道 `vec` 的确切类型,它只知道 `vec` 是一个含有某种类型 // 的 vector(`Vec<_>`)。 // 将 `elem` 插入 vector。 vec.push(elem); // Aha!现在编译器就知道了 `vec` 是一个含有 `u8` 类型的 vector(`Vec<u8>`) // 试一试 ^ 尝试将 `vec.push(elem)` 那行注释掉 println!("{:?}", vec); }
le
identifier_name
type_infer.rs
/* 类型推导引擎不仅仅在初始化期间分析右值的类型, 还会通过分析变量在后面是 怎么使用的来推导该变量的类型
// 创建一个空 vector(可增长数组)。 let mut vec = Vec::new(); // 此时编译器并未知道 `vec` 的确切类型,它只知道 `vec` 是一个含有某种类型 // 的 vector(`Vec<_>`)。 // 将 `elem` 插入 vector。 vec.push(elem); // Aha!现在编译器就知道了 `vec` 是一个含有 `u8` 类型的 vector(`Vec<u8>`) // 试一试 ^ 尝试将 `vec.push(elem)` 那行注释掉 println!("{:?}", vec); }
*/ fn main() { // 借助类型标注,编译器知道 `elem` 具有 u8 类型 let elem = 5u8;
random_line_split
a4.rs
fn main() { // Declaración de vectores o arrays let vector1 = vec!["primer lemento","segundo elemento","tercer elemento"] ; // Se utiliza "vec!" para declarar una apuntador de variable como vector. let mut vector2: Vec<&str> = Vec::new(); // Declaración de un vector vacío con el tipo de elementos que va a con...
println!("primer elemento vector 1: {} y tercer elemento vector 2: {}", vector1[0], vector2[2]); // También se puede consultar el índice de uno de los elementos del vector usando "[X]" junto al nombre del vecto, dónde X es el número de la posición del elemento. }
vector2 = vec!["Primero","Segundo"]; // Se agregan elementos al vector sobreescribiendolo gracias a "mut". vector2.push("Tercero"); // Agrega un elemento al final del vector. println!("primer vector 1: {:?} y segundo vector: {:?}", vector1, vector2); // Forma de ver en consola un vector no olvidar el ":?" entr...
random_line_split
a4.rs
fn main()
{ // Declaración de vectores o arrays let vector1 = vec!["primer lemento","segundo elemento","tercer elemento"] ; // Se utiliza "vec!" para declarar una apuntador de variable como vector. let mut vector2: Vec<&str> = Vec::new(); // Declaración de un vector vacío con el tipo de elementos que va a contener, en ...
identifier_body
a4.rs
fn
() { // Declaración de vectores o arrays let vector1 = vec!["primer lemento","segundo elemento","tercer elemento"] ; // Se utiliza "vec!" para declarar una apuntador de variable como vector. let mut vector2: Vec<&str> = Vec::new(); // Declaración de un vector vacío con el tipo de elementos que va a contener, ...
main
identifier_name
unique-enum.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
{ TheA { x: i64, y: i64 }, TheB (i64, i32, i32), } // This is a special case since it does not have the implicit discriminant field. enum Univariant { TheOnlyCase(i64) } fn main() { // In order to avoid endianness trouble all of the following test values consist of a single // repeated byte. Thi...
ABC
identifier_name
unique-enum.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
// 0b0001000100010001 = 4369 // 0b00010001 = 17 let the_b: Box<_> = box ABC::TheB (0, 286331153, 286331153); let univariant: Box<_> = box Univariant::TheOnlyCase(123234); zzz(); // #break } fn zzz() {()}
// 0b00010001000100010001000100010001 = 286331153
random_line_split
vertex.rs
//! Vertex data structures. use cgmath::{Point2,Point3,Vector2}; #[cfg(test)] use std::mem; use common::color::Color4; #[derive(Debug, Clone, Copy, PartialEq)] /// An untextured rendering vertex, with position and color. pub struct ColoredVertex { /// The 3-d position of this vertex in world space. pub position:...
}; [ vtx(min.x, min.y), vtx(max.x, max.y), vtx(min.x, max.y), vtx(min.x, min.y), vtx(max.x, min.y), vtx(max.x, max.y), ] } } #[derive(Debug, Clone, Copy, PartialEq)] /// A point in the world with corresponding texture data. /// /// The texture position is [0, 1]. pub struct TextureVertex {...
/// Generates two colored triangles, representing a square, at z=0. /// The bounds of the square is represented by `b`. pub fn square(min: Point2<f32>, max: Point2<f32>, color: Color4<f32>) -> [ColoredVertex; 6] { let vtx = |x, y| { ColoredVertex { position: Point3::new(x, y, 0.0), color: color }
random_line_split
vertex.rs
//! Vertex data structures. use cgmath::{Point2,Point3,Vector2}; #[cfg(test)] use std::mem; use common::color::Color4; #[derive(Debug, Clone, Copy, PartialEq)] /// An untextured rendering vertex, with position and color. pub struct ColoredVertex { /// The 3-d position of this vertex in world space. pub position:...
} #[derive(Debug, Clone, Copy, PartialEq)] /// A point in the world with corresponding texture data. /// /// The texture position is [0, 1]. pub struct TextureVertex { /// The position of this vertex in the world. pub world_position: Point3<f32>, /// The position of this vertex on a texture. The range of vali...
{ let vtx = |x, y| { ColoredVertex { position: Point3::new(x, y, 0.0), color: color } }; [ vtx(min.x, min.y), vtx(max.x, max.y), vtx(min.x, max.y), vtx(min.x, min.y), vtx(max.x, min.y), vtx(max.x, max.y), ] }
identifier_body
vertex.rs
//! Vertex data structures. use cgmath::{Point2,Point3,Vector2}; #[cfg(test)] use std::mem; use common::color::Color4; #[derive(Debug, Clone, Copy, PartialEq)] /// An untextured rendering vertex, with position and color. pub struct ColoredVertex { /// The 3-d position of this vertex in world space. pub position:...
{ /// The position of this vertex in the world. pub world_position: Point3<f32>, /// The position of this vertex on a texture. The range of valid values /// in each dimension is [0, 1]. pub texture_position: Vector2<f32>, }
TextureVertex
identifier_name
distinct_clause.rs
use crate::backend::Backend; use crate::query_builder::*; use crate::query_dsl::order_dsl::ValidOrderingForDistinct; use crate::result::QueryResult;
#[derive(Debug, Clone, Copy, QueryId)] pub struct NoDistinctClause; #[derive(Debug, Clone, Copy, QueryId)] pub struct DistinctClause; impl<DB: Backend> QueryFragment<DB> for NoDistinctClause { fn walk_ast(&self, _: AstPass<DB>) -> QueryResult<()> { Ok(()) } } impl<DB: Backend> QueryFragment<DB> for D...
random_line_split
distinct_clause.rs
use crate::backend::Backend; use crate::query_builder::*; use crate::query_dsl::order_dsl::ValidOrderingForDistinct; use crate::result::QueryResult; #[derive(Debug, Clone, Copy, QueryId)] pub struct
; #[derive(Debug, Clone, Copy, QueryId)] pub struct DistinctClause; impl<DB: Backend> QueryFragment<DB> for NoDistinctClause { fn walk_ast(&self, _: AstPass<DB>) -> QueryResult<()> { Ok(()) } } impl<DB: Backend> QueryFragment<DB> for DistinctClause { fn walk_ast(&self, mut out: AstPass<DB>) -> Que...
NoDistinctClause
identifier_name
chunk.rs
use std::io; use std::fmt; use std::ops::{Deref, DerefMut}; use ::aux::ReadExt; static NAME_LENGTH: u32 = 8; pub struct Root<R> { pub name: String, input: R, buffer: Vec<u8>, position: u32, } impl<R: io::Seek> Root<R> { pub fn tell(&mut self) -> u32 { self.input.seek(io::SeekFrom::Current...
pub fn ignore(self) { let left = self.end_pos - self.root.get_pos(); self.root.skip(left) } } impl<'a, R: io::Read> Drop for Chunk<'a, R> { fn drop(&mut self) { debug!("Leaving chunk"); assert!(!self.has_more()) } } impl<'a, R: io::Read> Deref for Chunk<'a, R> { t...
{ self.root.get_pos() < self.end_pos }
identifier_body
chunk.rs
use std::io; use std::fmt; use std::ops::{Deref, DerefMut}; use ::aux::ReadExt; static NAME_LENGTH: u32 = 8; pub struct Root<R> { pub name: String, input: R, buffer: Vec<u8>, position: u32, } impl<R: io::Seek> Root<R> { pub fn tell(&mut self) -> u32 { self.input.seek(io::SeekFrom::Current...
} }
} impl<'a, R: io::Read> DerefMut for Chunk<'a, R> { fn deref_mut(&mut self) -> &mut Root<R> { self.root
random_line_split
chunk.rs
use std::io; use std::fmt; use std::ops::{Deref, DerefMut}; use ::aux::ReadExt; static NAME_LENGTH: u32 = 8; pub struct Root<R> { pub name: String, input: R, buffer: Vec<u8>, position: u32, } impl<R: io::Seek> Root<R> { pub fn tell(&mut self) -> u32 { self.input.seek(io::SeekFrom::Current...
(&mut self) -> u8 { self.position += 1; self.input.read_u8().unwrap() } pub fn read_u32(&mut self) -> u32 { self.position += 4; self.input.read_u32().unwrap() } pub fn read_bool(&mut self) -> bool { self.position += 1; self.input.read_u8().unwrap()!= 0 ...
read_u8
identifier_name
xwrapper.rs
use libc::*; use std::ffi::{CString, CStr}; use std::ptr; use xlib::{ Display, Pixmap, Window, XClassHint, XCreateSimpleWindow, XDefaultScreen, XDefaultScreenOfDisplay, XGetSelectionOwner, XID, XInternAtom, XOpenDisplay, XRootWindowOfScreen, XSetSelectionOwner, XSizeHints }; use x11::xrender::{ XRenderCreatePicture, ...
} pub fn intern_atom(xserver: &XServer, name: &str) -> XID { return unsafe { XInternAtom(xserver.display, name.as_ptr() as *mut c_char, 0) }; } pub fn null_xrender_picture_attributes() -> XRenderPictureAttributes { return XRenderPictureAttributes { repeat: 0, alpha_map: XNone, alpha_x_origin: 0, ...
{ WindowSettings { opacity: intern_atom(xserver, "_NET_WM_WINDOW_OPACITY"), type_atom: intern_atom(xserver, "_NET_WM_WINDOW_TYPE"), is_desktop: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_DESKTOP"), is_dock: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_DOCK"), is_toolbar: intern_atom(xserver, "_NET_WM...
identifier_body
xwrapper.rs
use libc::*; use std::ffi::{CString, CStr}; use std::ptr; use xlib::{ Display, Pixmap, Window, XClassHint, XCreateSimpleWindow, XDefaultScreen, XDefaultScreenOfDisplay, XGetSelectionOwner, XID, XInternAtom, XOpenDisplay, XRootWindowOfScreen, XSetSelectionOwner, XSizeHints }; use x11::xrender::{ XRenderCreatePicture, ...
(xserver: &XServer) -> WindowSettings { WindowSettings { opacity: intern_atom(xserver, "_NET_WM_WINDOW_OPACITY"), type_atom: intern_atom(xserver, "_NET_WM_WINDOW_TYPE"), is_desktop: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_DESKTOP"), is_dock: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_DOCK"), is_...
find_window_settings
identifier_name
xwrapper.rs
use libc::*; use std::ffi::{CString, CStr}; use std::ptr; use xlib::{ Display, Pixmap, Window, XClassHint, XCreateSimpleWindow, XDefaultScreen, XDefaultScreenOfDisplay, XGetSelectionOwner, XID, XInternAtom, XOpenDisplay, XRootWindowOfScreen, XSetSelectionOwner, XSizeHints }; use x11::xrender::{ XRenderCreatePicture, ...
dither: XNone, component_alpha: 0, } } // // Side-Effecting Stuff // pub fn register_compositing_window_manager(xserver: &XServer, wm_name: &CStr) -> bool { let screen = unsafe { XDefaultScreen(xserver.display) }; let reg_atom_name = CString::new(format!("_NET_WM_CM_S{}", screen)).unwrap(); let reg_at...
graphics_exposures: 0, subwindow_mode: 0, poly_edge: 0, poly_mode: 0,
random_line_split
xwrapper.rs
use libc::*; use std::ffi::{CString, CStr}; use std::ptr; use xlib::{ Display, Pixmap, Window, XClassHint, XCreateSimpleWindow, XDefaultScreen, XDefaultScreenOfDisplay, XGetSelectionOwner, XID, XInternAtom, XOpenDisplay, XRootWindowOfScreen, XSetSelectionOwner, XSizeHints }; use x11::xrender::{ XRenderCreatePicture, ...
, _ => panic!(format!("Don't know how to query for {} extension", name)), } } } pub struct WindowSettings { pub opacity: XID, pub type_atom: XID, pub is_desktop: XID, pub is_dock: XID, pub is_toolbar: XID, pub is_menu: XID, pub is_util: XID, pub is_splash: XID, pub is_dialog: XID, pub i...
{ panic!("No XShape extension!"); }
conditional_block
list.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 http://mozilla.org/MPL/2.0/. */
${helpers.single_keyword("list-style-position", "outside inside", animatable=False)} // TODO(pcwalton): Implement the full set of counter styles per CSS-COUNTER-STYLES [1] 6.1: // // decimal-leading-zero, armenian, upper-armenian, lower-armenian, georgian, lower-roman, // upper-roman // // TODO(bholley): Miss...
<%namespace name="helpers" file="/helpers.mako.rs" /> <% data.new_style_struct("List", inherited=True) %>
random_line_split
list.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 http://mozilla.org/MPL/2.0/. */ <%namespace name="helpers" file="/helpers.mako.rs" /> <% data.new_style_struct("List", inherited=True) %> ${help...
} else { Err(()) } } </%helpers:longhand>
{ if input.try(|input| input.expect_ident_matching("none")).is_ok() { return Ok(SpecifiedValue(Vec::new())) } let mut quotes = Vec::new(); loop { let first = match input.next() { Ok(Token::QuotedString(value)) => value.into_owned(), ...
identifier_body
list.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 http://mozilla.org/MPL/2.0/. */ <%namespace name="helpers" file="/helpers.mako.rs" /> <% data.new_style_struct("List", inherited=True) %> ${help...
(pub Vec<(String,String)>); } impl ComputedValueAsSpecified for SpecifiedValue {} impl NoViewportPercentage for SpecifiedValue {} impl ToCss for SpecifiedValue { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { let mut first = true; for pair in &se...
T
identifier_name
template_installer.rs
// Copyright (C) 2020 Jason Ish // // 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, // ...
)); } let template_string = { if version.major >= 7 { crate::resource::get_string("elasticsearch/template-es7x.json").ok_or_else(|| { anyhow!( "Failed to find template for Elasticsearch version {}", version.version ...
{ debug!("Checking for template \"{}\"", template); match client.get_template(template).await { Err(err) => { warn!("Failed to check if template {} exists: {}", template, err); } Ok(None) => { debug!("Did not find template for \"{}\", will install", template); ...
identifier_body
template_installer.rs
// Copyright (C) 2020 Jason Ish // // 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, // ...
(client: &Client, template: &str) -> Result<()> { debug!("Checking for template \"{}\"", template); match client.get_template(template).await { Err(err) => { warn!("Failed to check if template {} exists: {}", template, err); } Ok(None) => { debug!("Did not find te...
install_template
identifier_name
template_installer.rs
// Copyright (C) 2020 Jason Ish // // 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, // ...
debug!("Checking for template \"{}\"", template); match client.get_template(template).await { Err(err) => { warn!("Failed to check if template {} exists: {}", template, err); } Ok(None) => { debug!("Did not find template for \"{}\", will install", template); ...
use anyhow::anyhow; use anyhow::Result; pub async fn install_template(client: &Client, template: &str) -> Result<()> {
random_line_split
template_installer.rs
// Copyright (C) 2020 Jason Ish // // 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, // ...
}; let version = client.get_version().await?; if version.major < 7 { return Err(anyhow!( "Elasticsearch version {} not supported", version.version )); } let template_string = { if version.major >= 7 { crate::resource::get_string("elastic...
{ debug!("Found template for \"{}\"", template); return Ok(()); }
conditional_block
filter.rs
use crate::fns::FnMut1; use core::fmt; use core::pin::Pin; use futures_core::future::Future; use futures_core::ready; use futures_core::stream::{FusedStream, Stream}; use futures_core::task::{Context, Poll}; #[cfg(feature = "sink")] use futures_sink::Sink; use pin_project_lite::pin_project; pin_project! { /// Stre...
(&self) -> (usize, Option<usize>) { let pending_len = if self.pending_item.is_some() { 1 } else { 0 }; let (_, upper) = self.stream.size_hint(); let upper = match upper { Some(x) => x.checked_add(pending_len), None => None, }; (0, upper) // can't know a lo...
size_hint
identifier_name
filter.rs
use crate::fns::FnMut1; use core::fmt; use core::pin::Pin; use futures_core::future::Future; use futures_core::ready; use futures_core::stream::{FusedStream, Stream}; use futures_core::task::{Context, Poll}; #[cfg(feature = "sink")] use futures_sink::Sink; use pin_project_lite::pin_project; pin_project! { /// Stre...
; let (_, upper) = self.stream.size_hint(); let upper = match upper { Some(x) => x.checked_add(pending_len), None => None, }; (0, upper) // can't know a lower bound, due to the predicate } } // Forwarding impl of Sink from the underlying stream #[cfg(feature ...
{ 0 }
conditional_block
filter.rs
use crate::fns::FnMut1; use core::fmt; use core::pin::Pin; use futures_core::future::Future; use futures_core::ready; use futures_core::stream::{FusedStream, Stream}; use futures_core::task::{Context, Poll}; #[cfg(feature = "sink")] use futures_sink::Sink; use pin_project_lite::pin_project; pin_project! { /// Stre...
{ type Item = St::Item; fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<St::Item>> { let mut this = self.project(); Poll::Ready(loop { if let Some(fut) = this.pending_fut.as_mut().as_pin_mut() { let res = ready!(fut.poll(cx)); ...
F: for<'a> FnMut1<&'a St::Item, Output = Fut>, Fut: Future<Output = bool>,
random_line_split