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
usb.rs
use std::io::Write; use libudev::{Result, Context, Enumerator}; use common::config::{self, MachineConfig, UsbId, UsbPort, UsbBinding, UsbDevice}; use common::usb_device::{UsbDevice as UsbDeviceInfo, Binding}; use ask; use wizard; #[derive(Clone, Copy, PartialEq, Eq)] pub enum HidKind { Mouse, Keyboard, } pu...
(kind: Option<HidKind>) -> Result<Vec<UsbDeviceInfo>> { let udev = Context::new().expect("Failed to create udev context"); let mut iter = Enumerator::new(&udev)?; iter.match_subsystem("usb")?; let devtype = if kind.is_some() { "usb_interface" } else { "usb_device" }; iter.match_property("DEVTYPE", d...
list_devices
identifier_name
usb.rs
use std::io::Write; use libudev::{Result, Context, Enumerator}; use common::config::{self, MachineConfig, UsbId, UsbPort, UsbBinding, UsbDevice}; use common::usb_device::{UsbDevice as UsbDeviceInfo, Binding}; use ask; use wizard; #[derive(Clone, Copy, PartialEq, Eq)] pub enum HidKind { Mouse, Keyboard, } pu...
} } } else { // device not connected match dev.binding { UsbBinding::ById(id) => { let info = UsbDeviceInfo::from_id(id); println!("[{}]\t{} (Not Connected)", i, info); ...
{ let infos = list_devices(None).expect("Can't read connected USB devices"); loop { println!("You have currently selected the following usb devices: "); let mut last = 0; for (i, dev) in usb_devices.iter().cloned().enumerate() { if let Some(pos) = infos.iter().position(|info...
identifier_body
usb.rs
use std::io::Write; use libudev::{Result, Context, Enumerator}; use common::config::{self, MachineConfig, UsbId, UsbPort, UsbBinding, UsbDevice}; use common::usb_device::{UsbDevice as UsbDeviceInfo, Binding}; use ask; use wizard; #[derive(Clone, Copy, PartialEq, Eq)] pub enum HidKind { Mouse, Keyboard, } pu...
println!(); true } /// Lets the user remove (some) of given devices /// /// This modifies the passed list. fn remove(usb_devices: &mut Vec<UsbDevice>) { let infos = list_devices(None).expect("Can't read connected USB devices"); loop { println!("You have currently selected the following usb dev...
}).expect("Cannot write udev rules");
random_line_split
token.rs
//! Traits and enums dealing with Tokenization of printf Format String #[allow(unused_must_use)] use std::iter::Peekable; use std::str::Chars; use std::slice::Iter; use itertools::PutBackN; // A token object is an object that can print the expected output // of a contiguous segment of the format string, and
} // A tokenizer object is an object that takes an iterator // at a position in a format string, and sees whether // it can return a token of a type it knows how to produce // if so, return the token, move the iterator past the // format string text the token represents, and if an // argument is used move the argument...
// requires at most 1 argusegment pub trait Token { fn print(&self, args: &mut Peekable<Iter<String>>);
random_line_split
htmltablecellelement.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 cssparser::RGBA; use dom::bindings::codegen::Bindings::HTMLTableCellElementBinding::HTMLTableCellElementMethod...
impl HTMLTableCellElementMethods for HTMLTableCellElement { // https://html.spec.whatwg.org/multipage/#dom-tdth-colspan make_uint_getter!(ColSpan, "colspan", DEFAULT_COLSPAN); // https://html.spec.whatwg.org/multipage/#dom-tdth-colspan make_uint_setter!(SetColSpan, "colspan", DEFAULT_COLSPAN); // ...
} }
random_line_split
htmltablecellelement.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 cssparser::RGBA; use dom::bindings::codegen::Bindings::HTMLTableCellElementBinding::HTMLTableCellElementMethod...
(tag_name: LocalName, prefix: Option<DOMString>, document: &Document) -> HTMLTableCellElement { HTMLTableCellElement { htmlelement: HTMLElement::new_inherited(tag_name, prefix, document), } } } impl HTMLTableCell...
new_inherited
identifier_name
rpc.rs
extern crate rustc_serialize; use std::collections::HashMap; use rustc_serialize::json::Json; use std::sync::{RwLock}; #[derive(RustcDecodable)] pub struct RpcCall { id: u32, method: String, params: Vec<String> } #[derive(RustcEncodable)] pub struct RpcResponse { id: u32, result: Json, error: Json } pub stru...
match result { Ok(data) => RpcResponse{id: req.id, result: Json::String(data), error: Json::Null}, Err(e) => RpcResponse{id: req.id, result: Json::Null, error: Json::String(e)}, } } pub fn register_function<F: Fn(&T, Vec<String>) -> Result<String, String> + Sync + Send +'static>(&mut self, s: &str, f:...
None => Err(format!("Unknown method: {}", req.method)) };
random_line_split
rpc.rs
extern crate rustc_serialize; use std::collections::HashMap; use rustc_serialize::json::Json; use std::sync::{RwLock}; #[derive(RustcDecodable)] pub struct
{ id: u32, method: String, params: Vec<String> } #[derive(RustcEncodable)] pub struct RpcResponse { id: u32, result: Json, error: Json } pub struct RpcApi<T> { api_impl: RwLock<Box<T>>, method_mappings: RwLock<HashMap<String, RwLock<Box<Fn(&T, Vec<String>) -> Result<String,String> + Sync + Send>>>>, } impl...
RpcCall
identifier_name
rpc.rs
extern crate rustc_serialize; use std::collections::HashMap; use rustc_serialize::json::Json; use std::sync::{RwLock}; #[derive(RustcDecodable)] pub struct RpcCall { id: u32, method: String, params: Vec<String> } #[derive(RustcEncodable)] pub struct RpcResponse { id: u32, result: Json, error: Json } pub stru...
, None => Err(format!("Unknown method: {}", req.method)) }; match result { Ok(data) => RpcResponse{id: req.id, result: Json::String(data), error: Json::Null}, Err(e) => RpcResponse{id: req.id, result: Json::Null, error: Json::String(e)}, } } pub fn register_function<F: Fn(&T, Vec<String>) -> Res...
{ let api = self.api_impl.read().unwrap(); let mapping = mapping_lock.read().unwrap(); mapping(&(*api), req.params) }
conditional_block
method-mangling.rs
#![allow( dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals )] #[repr(C)] #[derive(Debug, Default, Copy, Clone)] pub struct Foo { pub _address: u8, } #[test] fn
() { assert_eq!( ::std::mem::size_of::<Foo>(), 1usize, concat!("Size of: ", stringify!(Foo)) ); assert_eq!( ::std::mem::align_of::<Foo>(), 1usize, concat!("Alignment of ", stringify!(Foo)) ); } extern "C" { #[link_name = "\u{1}_ZN3Foo4typeEv"] pub ...
bindgen_test_layout_Foo
identifier_name
method-mangling.rs
#![allow( dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals )] #[repr(C)] #[derive(Debug, Default, Copy, Clone)] pub struct Foo { pub _address: u8, } #[test] fn bindgen_test_layout_Foo() { assert_eq!( ::std::mem::size_of::<Foo>(), 1usize, concat!("S...
} impl Foo { #[inline] pub unsafe fn type_(&mut self) -> ::std::os::raw::c_int { Foo_type(self) } }
#[link_name = "\u{1}_ZN3Foo4typeEv"] pub fn Foo_type(this: *mut Foo) -> ::std::os::raw::c_int;
random_line_split
chario.rs
// Zinc, the bare metal stack for rust. // Copyright 2014 Vladimir "farcaller" Pouzanov <farcaller@gmail.com> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.o...
self.putc(i as char); } } /// Outputs an integer. fn puti(&self, i: u32) { self.putint(i, 10); } /// Outputs an integer as a hex string. fn puth(&self, i: u32) { self.putint(i, 16); } } #[cfg(test)] pub mod test { use core::cell::RefCell; use drivers::chario::CharIO; #[derive...
{ break; }
conditional_block
chario.rs
// Zinc, the bare metal stack for rust. // Copyright 2014 Vladimir "farcaller" Pouzanov <farcaller@gmail.com> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.o...
/// Outputs an integer. fn puti(&self, i: u32) { self.putint(i, 10); } /// Outputs an integer as a hex string. fn puth(&self, i: u32) { self.putint(i, 16); } } #[cfg(test)] pub mod test { use core::cell::RefCell; use drivers::chario::CharIO; #[derive(Copy)] pub struct TestCharIOData { ...
random_line_split
chario.rs
// Zinc, the bare metal stack for rust. // Copyright 2014 Vladimir "farcaller" Pouzanov <farcaller@gmail.com> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.o...
fn get_and_reset_putc_calls(&self) -> usize { let current = self.data.borrow().putc_calls; self.data.borrow_mut().putc_calls = 0; current } } #[test] fn putc_should_store_a_char() { let io = TestCharIO::new(); io.putc('a'); assert!(io.get_last_char() == 'a'); io.putc('...
{ self.data.borrow().last_char }
identifier_body
chario.rs
// Zinc, the bare metal stack for rust. // Copyright 2014 Vladimir "farcaller" Pouzanov <farcaller@gmail.com> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.o...
(&self, i: u32) { self.putint(i, 10); } /// Outputs an integer as a hex string. fn puth(&self, i: u32) { self.putint(i, 16); } } #[cfg(test)] pub mod test { use core::cell::RefCell; use drivers::chario::CharIO; #[derive(Copy)] pub struct TestCharIOData { last_char: char, putc_calls: ...
puti
identifier_name
mod.rs
/* * Copyright 2013 Hayden Smith * * 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 t...
impl Send for Parser {} impl Emitter for Parser { fn emit(&mut self, cmsp: Option<(&CodeMap, Span)>, msg: &str, code: Option<&str>, lvl: Level) { } fn custom_emit(&mut self, cm: &CodeMap, sp: RenderSpan, msg: &str, lvl: Level) { } }
} } // TODO This is probably not a good idea
random_line_split
mod.rs
/* * Copyright 2013 Hayden Smith * * 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 t...
(&mut self, cmsp: Option<(&CodeMap, Span)>, msg: &str, code: Option<&str>, lvl: Level) { } fn custom_emit(&mut self, cm: &CodeMap, sp: RenderSpan, msg: &str, lvl: Level) { } }
emit
identifier_name
mod.rs
/* * Copyright 2013 Hayden Smith * * 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 t...
} // TODO This is probably not a good idea impl Send for Parser {} impl Emitter for Parser { fn emit(&mut self, cmsp: Option<(&CodeMap, Span)>, msg: &str, code: Option<&str>, lvl: Level) { } fn custom_emit(&mut self, cm: &CodeMap, sp: RenderSpan, msg: &str, lvl: Level) { } }
{ // TODO use diagnostic emitter? let parse_session = new_parse_sess_special_handler(mk_span_handler(mk_handler(box *self), CodeMap::new())); let cfg: ast::CrateConfig = Vec::new(); let mut c = parse_crate_from_source_str(String::from_str(name), String::from_str(source), cfg.clone(), &parse_session); //...
identifier_body
icmp.rs
use network::common::*; use network::icmp::*;
use programs::common::*; pub struct ICMPScheme; impl SessionItem for ICMPScheme { fn scheme(&self) -> String { return "icmp".to_string(); } } impl ICMPScheme { pub fn reply_loop(){ loop{ let mut ip = URL::from_str("ip:///1").open(); let mut bytes: Vec<u8> = Vec::...
random_line_split
icmp.rs
use network::common::*; use network::icmp::*; use programs::common::*; pub struct ICMPScheme; impl SessionItem for ICMPScheme { fn scheme(&self) -> String { return "icmp".to_string(); } } impl ICMPScheme { pub fn reply_loop()
response.header.checksum.data = Checksum::compile( Checksum::sum(header_ptr as usize, size_of::<ICMPHeader>()) + Checksum::sum(response.data.as_ptr() as usize, response.data.len()) ); ...
{ loop{ let mut ip = URL::from_str("ip:///1").open(); let mut bytes: Vec<u8> = Vec::new(); match ip.read_to_end(&mut bytes) { Option::Some(_) => { if let Option::Some(message) = ICMP::from_bytes(bytes) { if message....
identifier_body
icmp.rs
use network::common::*; use network::icmp::*; use programs::common::*; pub struct ICMPScheme; impl SessionItem for ICMPScheme { fn scheme(&self) -> String { return "icmp".to_string(); } } impl ICMPScheme { pub fn reply_loop(){ loop{ let mut ip = URL::from_str("ip:///1").open(...
} } }, Option::None => sys_yield() } } } }
{ if message.header._type == 0x08 { let mut response = ICMP { header: message.header, data: message.data }; response.header._type = 0x00; ...
conditional_block
icmp.rs
use network::common::*; use network::icmp::*; use programs::common::*; pub struct ICMPScheme; impl SessionItem for ICMPScheme { fn scheme(&self) -> String { return "icmp".to_string(); } } impl ICMPScheme { pub fn
(){ loop{ let mut ip = URL::from_str("ip:///1").open(); let mut bytes: Vec<u8> = Vec::new(); match ip.read_to_end(&mut bytes) { Option::Some(_) => { if let Option::Some(message) = ICMP::from_bytes(bytes) { if messag...
reply_loop
identifier_name
swizzle.rs
use crate::base::allocator::Allocator; use crate::base::{DefaultAllocator, DimName, Scalar}; use crate::geometry::{Point, Point2, Point3}; use typenum::{self, Cmp, Greater}; macro_rules! impl_swizzle { ($( where $BaseDim: ident: $( $name: ident() -> $Result: ident[$($i: expr),+] ),+ ;)* ) => { $( ...
D::Value: Cmp<typenum::$BaseDim, Output=Greater> { $( /// Builds a new point from components of `self`. #[inline] pub fn $name(&self) -> $Result<N> { $Result::new($(self[$i].inlined_clone()),*...
DefaultAllocator: Allocator<N, D>,
random_line_split
mod.rs
/* Copyright (C) 2017-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...
pub mod ikev2; pub mod state; pub mod log;
// written by Pierre Chifflier <chifflier@wzdftpd.net> extern crate ipsec_parser;
random_line_split
kmerge.rs
use std::cmp::Ordering; use std::cmp::Reverse; use std::collections::BinaryHeap; #[derive(Debug, Eq)] struct Item<'a> { arr: &'a Vec<i32>, idx: usize, } impl<'a> PartialEq for Item<'a> { fn eq(&self, other: &Self) -> bool { self.get_item() == other.get_item() } } impl<'a> PartialOrd for Item<...
} sorted } fn main() { let a = vec![1, 5, 7]; let b = vec![-2, 3, 4]; let v = vec![a, b]; dbg!(merge(v)); }
{ heap.push(it) }
conditional_block
kmerge.rs
use std::cmp::Ordering; use std::cmp::Reverse; use std::collections::BinaryHeap; #[derive(Debug, Eq)] struct Item<'a> { arr: &'a Vec<i32>, idx: usize, } impl<'a> PartialEq for Item<'a> { fn eq(&self, other: &Self) -> bool { self.get_item() == other.get_item() } } impl<'a> PartialOrd for Item<...
impl<'a> Ord for Item<'a> { fn cmp(&self, other: &Self) -> Ordering { self.get_item().cmp(&other.get_item()) } } impl<'a> Item<'a> { fn new(arr: &'a Vec<i32>, idx: usize) -> Self { Self { arr, idx } } fn get_item(&self) -> i32 { self.arr[self.idx] } } fn merge(arrays:...
self.get_item().partial_cmp(&other.get_item()) } }
random_line_split
kmerge.rs
use std::cmp::Ordering; use std::cmp::Reverse; use std::collections::BinaryHeap; #[derive(Debug, Eq)] struct Item<'a> { arr: &'a Vec<i32>, idx: usize, } impl<'a> PartialEq for Item<'a> { fn eq(&self, other: &Self) -> bool
} impl<'a> PartialOrd for Item<'a> { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { self.get_item().partial_cmp(&other.get_item()) } } impl<'a> Ord for Item<'a> { fn cmp(&self, other: &Self) -> Ordering { self.get_item().cmp(&other.get_item()) } } impl<'a> Item<'a> { f...
{ self.get_item() == other.get_item() }
identifier_body
kmerge.rs
use std::cmp::Ordering; use std::cmp::Reverse; use std::collections::BinaryHeap; #[derive(Debug, Eq)] struct Item<'a> { arr: &'a Vec<i32>, idx: usize, } impl<'a> PartialEq for Item<'a> { fn eq(&self, other: &Self) -> bool { self.get_item() == other.get_item() } } impl<'a> PartialOrd for Item<...
(arrays: Vec<Vec<i32>>) -> Vec<i32> { let mut sorted = vec![]; let mut heap = BinaryHeap::with_capacity(arrays.len()); // From each vector we build an item which // stores the array and the current index. for arr in &arrays { let item = Item::new(arr, 0); println!("item={:?}", item...
merge
identifier_name
console.rs
// Legato - Statsd Server in Rust // // Copyright 2016 TSH Labs // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or d...
} } impl fmt::Display for ConsoleMetricSink { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { "console metric backend".fmt(f) } } impl MetricSink for ConsoleMetricSink { fn accept(&mut self, metrics: &AggregatedMetrics) -> MetricResult<()> { let now = time::get_time(); ...
/// Create a new console `MetricSink` pub fn new() -> ConsoleMetricSink { ConsoleMetricSink { formatter: GraphiteMetricFormatter::new() }
random_line_split
console.rs
// Legato - Statsd Server in Rust // // Copyright 2016 TSH Labs // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or d...
(&self, f: &mut fmt::Formatter) -> fmt::Result { "console metric backend".fmt(f) } } impl MetricSink for ConsoleMetricSink { fn accept(&mut self, metrics: &AggregatedMetrics) -> MetricResult<()> { let now = time::get_time(); let counters = metrics.counters(); let timers = metr...
fmt
identifier_name
console.rs
// Legato - Statsd Server in Rust // // Copyright 2016 TSH Labs // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or d...
} impl MetricSink for ConsoleMetricSink { fn accept(&mut self, metrics: &AggregatedMetrics) -> MetricResult<()> { let now = time::get_time(); let counters = metrics.counters(); let timers = metrics.timers(); let gauges = metrics.gauges(); debug!("Flushing {} counters to ...
{ "console metric backend".fmt(f) }
identifier_body
console.rs
// Legato - Statsd Server in Rust // // Copyright 2016 TSH Labs // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or d...
Ok(()) } }
{ print!("{}", self.formatter.fmt_gauges(metrics.gauges(), &now)); }
conditional_block
tree.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/. */ //! Traits that nodes must implement. Breaks the otherwise-cyclic dependency //! between layout and style. use c...
/// Whether this element and the `other` element have the same local name and namespace. fn is_same_type(&self, other: &Self) -> bool; fn attr_matches( &self, ns: &NamespaceConstraint<&<Self::Impl as SelectorImpl>::NamespaceUrl>, local_name: &<Self::Impl as SelectorImpl>::LocalName...
fn has_namespace(&self, ns: &<Self::Impl as SelectorImpl>::BorrowedNamespaceUrl) -> bool;
random_line_split
tree.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/. */ //! Traits that nodes must implement. Breaks the otherwise-cyclic dependency //! between layout and style. use c...
(NonNull<()>); unsafe impl Send for OpaqueElement {} impl OpaqueElement { /// Creates a new OpaqueElement from an arbitrarily-typed pointer. pub fn new<T>(ptr: &T) -> Self { unsafe { OpaqueElement(NonNull::new_unchecked( ptr as *const T as *const () as *mut (), ...
OpaqueElement
identifier_name
tree.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/. */ //! Traits that nodes must implement. Breaks the otherwise-cyclic dependency //! between layout and style. use c...
fn has_id( &self, id: &<Self::Impl as SelectorImpl>::Identifier, case_sensitivity: CaseSensitivity, ) -> bool; fn has_class( &self, name: &<Self::Impl as SelectorImpl>::ClassName, case_sensitivity: CaseSensitivity, ) -> bool; fn is_part(&self, name...
{ None }
identifier_body
echo_bot.rs
extern crate serde; extern crate serde_json as json; extern crate tweetust; extern crate twitter_stream; use std::fs::File; use std::path::PathBuf; use serde::de; use serde::Deserialize; use twitter_stream::rt::{self, Future, Stream}; use twitter_stream::{Error, Token, TwitterStreamBuilder}; #[derive(Deserialize)] #...
token, tweetust::DefaultHttpHandler::with_https_connector().unwrap(), ); // Information of the authenticated user: let user = rest .account() .verify_credentials() .execute() .unwrap() .object; let bot = stream .for_each(move |json| { ...
random_line_split
echo_bot.rs
extern crate serde; extern crate serde_json as json; extern crate tweetust; extern crate twitter_stream; use std::fs::File; use std::path::PathBuf; use serde::de; use serde::Deserialize; use twitter_stream::rt::{self, Future, Stream}; use twitter_stream::{Error, Token, TwitterStreamBuilder}; #[derive(Deserialize)] #...
} Ok(()) }) .map_err(|e| println!("error: {}", e)); rt::run(bot); }
{ println!( "On {}, @{} tweeted: {:?}", tweet.created_at, tweet.user.screen_name, tweet.text ); let response = format!("@{} {}", tweet.user.screen_name, tweet.text); rest.statuses() ...
conditional_block
echo_bot.rs
extern crate serde; extern crate serde_json as json; extern crate tweetust; extern crate twitter_stream; use std::fs::File; use std::path::PathBuf; use serde::de; use serde::Deserialize; use twitter_stream::rt::{self, Future, Stream}; use twitter_stream::{Error, Token, TwitterStreamBuilder}; #[derive(Deserialize)] #...
{ Tweet(Tweet), Other(de::IgnoredAny), } #[derive(Deserialize)] struct Tweet { created_at: String, entities: Entities, id: i64, text: String, user: User, } #[derive(Deserialize)] struct Entities { user_mentions: Vec<UserMention>, } #[derive(Deserialize)] struct UserMention { id: ...
StreamMessage
identifier_name
listen.rs
// Copyright (c) 2020 DDN. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. use crate::{cache, db_record, error, users, DbRecord}; use futures::{Stream, TryStreamExt}; use iml_wire_types::{ db::TableName, warp_drive::{Message, RecordCh...
while let Some(msg) = stream.try_next().await? { let api_cache_state = Arc::clone(&api_cache_state); let user_state = Arc::clone(&user_state); match msg { iml_postgres::AsyncMessage::Notification(n) => { if n.channel() == "table_update" { let...
// Keep the client alive within the spawned future so the LISTEN/NOTIFY stream is not dropped let _keep_alive = &client;
random_line_split
listen.rs
// Copyright (c) 2020 DDN. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. use crate::{cache, db_record, error, users, DbRecord}; use futures::{Stream, TryStreamExt}; use iml_wire_types::{ db::TableName, warp_drive::{Message, RecordCh...
Ok(()) } iml_postgres::AsyncMessage::Notice(err) => { tracing::error!("Error from postgres {}", err); Err(error::ImlWarpDriveError::from(err)) } _ => unreachable!(), }?; } Ok(()) }
{ // Keep the client alive within the spawned future so the LISTEN/NOTIFY stream is not dropped let _keep_alive = &client; while let Some(msg) = stream.try_next().await? { let api_cache_state = Arc::clone(&api_cache_state); let user_state = Arc::clone(&user_state); match msg { ...
identifier_body
listen.rs
// Copyright (c) 2020 DDN. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. use crate::{cache, db_record, error, users, DbRecord}; use futures::{Stream, TryStreamExt}; use iml_wire_types::{ db::TableName, warp_drive::{Message, RecordCh...
(s: &str) -> serde_json::error::Result<(MessageType, DbRecord)> { let (msg_type, table_name, x): (MessageType, TableName, serde_json::Value) = serde_json::from_str(&s)?; let r = db_record::DbRecord::try_from((table_name, x))?; Ok((msg_type, r)) } async fn handle_record_change( record_change: ...
into_db_record
identifier_name
p021.rs
//! [Problem 21](https://projecteuler.net/problem=21) solver. #![warn( bad_style, unused, unused_extern_crates, unused_import_braces, unused_qualifications, unused_results )] use prime::{Factorize, PrimeSet}; fn compute(limit: u64) -> u64 { let ps = PrimeSet::new(); let sum_of_div = ...
common::problem!("31626", solve);
{ compute(10000).to_string() }
identifier_body
p021.rs
//! [Problem 21](https://projecteuler.net/problem=21) solver. #![warn( bad_style, unused, unused_extern_crates, unused_import_braces, unused_qualifications, unused_results )] use prime::{Factorize, PrimeSet}; fn compute(limit: u64) -> u64 { let ps = PrimeSet::new(); let sum_of_div = ...
() -> String { compute(10000).to_string() } common::problem!("31626", solve);
solve
identifier_name
p021.rs
//! [Problem 21](https://projecteuler.net/problem=21) solver. #![warn( bad_style, unused, unused_extern_crates, unused_import_braces, unused_qualifications, unused_results )] use prime::{Factorize, PrimeSet}; fn compute(limit: u64) -> u64 { let ps = PrimeSet::new(); let sum_of_div = ...
.enumerate() .map(|(n, div)| (n as u64, div)) .filter(|&(n, div)| div < n) .filter(|&(n, div)| sum_of_div[div as usize] == n) .map(|(a, b)| a + b) .sum() } fn solve() -> String { compute(10000).to_string() } common::problem!("31626", solve);
.collect::<Vec<_>>(); sum_of_div .iter() .cloned()
random_line_split
ipv4_udp.rs
use alloc::vec::Vec; use crate::checksum::inet_checksum; use crate::ipv4; use crate::udp; use crate::{IpProtocol, Ipv4Addr}; pub struct
{ pub ipv4_header: ipv4::Header, pub udp_header: udp::Header, pub payload: Vec<u8>, } impl Builder { /// TODO: fragmentation support pub fn new( src_ip: Ipv4Addr, dst_ip: Ipv4Addr, src_port: u16, dst_port: u16, payload: Vec<u8>, ) -> Self { Self { ipv4_header: ipv4::...
Builder
identifier_name
ipv4_udp.rs
use alloc::vec::Vec;
use crate::ipv4; use crate::udp; use crate::{IpProtocol, Ipv4Addr}; pub struct Builder { pub ipv4_header: ipv4::Header, pub udp_header: udp::Header, pub payload: Vec<u8>, } impl Builder { /// TODO: fragmentation support pub fn new( src_ip: Ipv4Addr, dst_ip: Ipv4Addr, src_port: u16, dst_port...
use crate::checksum::inet_checksum;
random_line_split
stock_server.rs
mod async_helpers; use rand::Rng; use std::time::Duration; use zeromq::*; #[async_helpers::main] async fn main() -> Result<(), Box<dyn std::error::Error>>
{ let mut rng = rand::thread_rng(); let stocks: Vec<&str> = vec!["AAA", "ABB", "BBB"]; println!("Starting server"); let mut socket = zeromq::PubSocket::new(); socket.bind("tcp://127.0.0.1:5556").await?; println!("Start sending loop"); loop { for stock in &stocks { let pr...
identifier_body
stock_server.rs
mod async_helpers; use rand::Rng; use std::time::Duration; use zeromq::*; #[async_helpers::main] async fn
() -> Result<(), Box<dyn std::error::Error>> { let mut rng = rand::thread_rng(); let stocks: Vec<&str> = vec!["AAA", "ABB", "BBB"]; println!("Starting server"); let mut socket = zeromq::PubSocket::new(); socket.bind("tcp://127.0.0.1:5556").await?; println!("Start sending loop"); loop { ...
main
identifier_name
stock_server.rs
mod async_helpers; use rand::Rng; use std::time::Duration; use zeromq::*; #[async_helpers::main] async fn main() -> Result<(), Box<dyn std::error::Error>> { let mut rng = rand::thread_rng(); let stocks: Vec<&str> = vec!["AAA", "ABB", "BBB"]; println!("Starting server"); let mut socket = zeromq::PubSoc...
}
random_line_split
minschannel.rs
// Copyright © 2015, Peter Atashian // Licensed under the MIT License <LICENSE.md> //! Public Definitions for MIN SCHANNEL Security Provider pub const SECPKG_ATTR_ISSUER_LIST: ::DWORD = 0x50; pub const SECPKG_ATTR_REMOTE_CRED: ::DWORD = 0x51; pub const SECPKG_ATTR_LOCAL_CRED: ::DWORD = 0x52; pub const SECPKG_AT...
pub const SECPKG_ATTR_USE_NCRYPT: ::DWORD = 0x62; pub const SECPKG_ATTR_LOCAL_CERT_INFO: ::DWORD = 0x63; pub const SECPKG_ATTR_CIPHER_INFO: ::DWORD = 0x64; pub const SECPKG_ATTR_EAP_PRF_INFO: ::DWORD = 0x65; pub const SECPKG_ATTR_SUPPORTED_SIGNATURES: ::DWORD = 0x66; pub const SECPKG_ATTR_REMOTE_CERT_CHAIN: ::DWOR...
random_line_split
instr_mulps.rs
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; use ::RegType::*; use ::instruction_def::*; use ::Operand::*; use ::Reg::*; use ::RegScale::*; use ::test::run_test;
#[test] fn mulps_2() { run_test(&Instruction { mnemonic: Mnemonic::MULPS, operand1: Some(Direct(XMM6)), operand2: Some(Indirect(EBX, Some(OperandSize::Xmmword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[15, 89, 51], Opera...
#[test] fn mulps_1() { run_test(&Instruction { mnemonic: Mnemonic::MULPS, operand1: Some(Direct(XMM3)), operand2: Some(Direct(XMM7)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[15, 89, 223], OperandSize::Dword) }
random_line_split
instr_mulps.rs
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; use ::RegType::*; use ::instruction_def::*; use ::Operand::*; use ::Reg::*; use ::RegScale::*; use ::test::run_test; #[test] fn mulps_1() { run_test(&Instruction { mnemonic: Mnemonic::MULPS, operand1: Some(Direct(XMM3...
() { run_test(&Instruction { mnemonic: Mnemonic::MULPS, operand1: Some(Direct(XMM1)), operand2: Some(IndirectDisplaced(RCX, 674850177, Some(OperandSize::Xmmword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[15, 89, 137, 129...
mulps_4
identifier_name
instr_mulps.rs
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; use ::RegType::*; use ::instruction_def::*; use ::Operand::*; use ::Reg::*; use ::RegScale::*; use ::test::run_test; #[test] fn mulps_1() { run_test(&Instruction { mnemonic: Mnemonic::MULPS, operand1: Some(Direct(XMM3...
{ run_test(&Instruction { mnemonic: Mnemonic::MULPS, operand1: Some(Direct(XMM1)), operand2: Some(IndirectDisplaced(RCX, 674850177, Some(OperandSize::Xmmword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[15, 89, 137, 129, 1...
identifier_body
do_for_ever4.rs
fn make_a_division_for_ever() { loop { println!("Enter divisor..."); let line_resutl :Result<String, std::io::IoError> = std::io::stdin().read_line(); let line_string : String = match line_resutl { Ok(line) => line, Err(why) => why.desc.to_string(), }; ...
let dangerous : u32 = 1_000_000 / divisor; println!("DIV RESULT... {}", dangerous); } }
None => { println!("Invalid value, I will die"); panic!("Invalid value") } } println!("readed {}", readed_u32);
random_line_split
do_for_ever4.rs
fn make_a_division_for_ever()
println!("readed {}", readed_u32); let dangerous : u32 = 1_000_000 / divisor; println!("DIV RESULT... {}", dangerous); } }
{ loop { println!("Enter divisor..."); let line_resutl :Result<String, std::io::IoError> = std::io::stdin().read_line(); let line_string : String = match line_resutl { Ok(line) => line, Err(why) => why.desc.to_string(), }; let line_string_trimmed :...
identifier_body
do_for_ever4.rs
fn
() { loop { println!("Enter divisor..."); let line_resutl :Result<String, std::io::IoError> = std::io::stdin().read_line(); let line_string : String = match line_resutl { Ok(line) => line, Err(why) => why.desc.to_string(), }; let line_string_trimme...
make_a_division_for_ever
identifier_name
result.rs
//! Error types that can be emitted from this library use std::error::Error; use std::fmt; use std::io; /// Generic result type with ZipError as its error variant pub type ZipResult<T> = Result<T, ZipError>; /// The given password is wrong #[derive(Debug)] pub struct InvalidPassword; impl fmt::Display for InvalidPa...
} impl fmt::Display for ZipError { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { match self { ZipError::Io(err) => write!(fmt, "{}", err), ZipError::InvalidArchive(err) => write!(fmt, "invalid Zip archive: {}", err), ZipError::UnsupportedArchive(err) => write...
{ ZipError::Io(err) }
identifier_body
result.rs
//! Error types that can be emitted from this library use std::error::Error; use std::fmt; use std::io; /// Generic result type with ZipError as its error variant pub type ZipResult<T> = Result<T, ZipError>; /// The given password is wrong #[derive(Debug)] pub struct InvalidPassword; impl fmt::Display for InvalidPa...
(err: io::Error) -> ZipError { ZipError::Io(err) } } impl fmt::Display for ZipError { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { match self { ZipError::Io(err) => write!(fmt, "{}", err), ZipError::InvalidArchive(err) => write!(fmt, "invalid Zip archive: {}"...
from
identifier_name
result.rs
//! Error types that can be emitted from this library use std::error::Error; use std::fmt; use std::io; /// Generic result type with ZipError as its error variant pub type ZipResult<T> = Result<T, ZipError>; /// The given password is wrong #[derive(Debug)] pub struct InvalidPassword; impl fmt::Display for InvalidPa...
pub enum ZipError { /// An Error caused by I/O Io(io::Error), /// This file is probably not a zip archive InvalidArchive(&'static str), /// This archive is not supported UnsupportedArchive(&'static str), /// The requested file could not be found in the archive FileNotFound, } impl Fr...
random_line_split
arbitrary_enum_discriminant.rs
// run-pass #![feature(arbitrary_enum_discriminant, test)] extern crate test; use test::black_box; #[allow(dead_code)] #[repr(u8)] enum Enum { Unit = 3, Tuple(u16) = 2, Struct { a: u8, b: u16, } = 1, } impl Enum { const unsafe fn tag(&self) -> u8 { *(self as *const Self a...
{ Unit = 3, Tuple() = 2, Struct {} = 1, } fn main() { const UNIT: Enum = Enum::Unit; const TUPLE: Enum = Enum::Tuple(5); const STRUCT: Enum = Enum::Struct{a: 7, b: 11}; // Ensure discriminants are correct during runtime execution assert_eq!(3, unsafe { black_box(UNIT).tag() }); as...
FieldlessEnum
identifier_name
arbitrary_enum_discriminant.rs
// run-pass #![feature(arbitrary_enum_discriminant, test)] extern crate test; use test::black_box; #[allow(dead_code)] #[repr(u8)] enum Enum { Unit = 3, Tuple(u16) = 2, Struct { a: u8, b: u16, } = 1, } impl Enum { const unsafe fn tag(&self) -> u8 { *(self as *const Self a...
assert_eq!(3, FieldlessEnum::Unit as u8); assert_eq!(2, FieldlessEnum::Tuple() as u8); assert_eq!(1, FieldlessEnum::Struct{} as u8); }
{ const UNIT: Enum = Enum::Unit; const TUPLE: Enum = Enum::Tuple(5); const STRUCT: Enum = Enum::Struct{a: 7, b: 11}; // Ensure discriminants are correct during runtime execution assert_eq!(3, unsafe { black_box(UNIT).tag() }); assert_eq!(2, unsafe { black_box(TUPLE).tag() }); assert_eq!(1, ...
identifier_body
arbitrary_enum_discriminant.rs
// run-pass #![feature(arbitrary_enum_discriminant, test)] extern crate test; use test::black_box; #[allow(dead_code)] #[repr(u8)] enum Enum { Unit = 3, Tuple(u16) = 2, Struct { a: u8, b: u16, } = 1, } impl Enum { const unsafe fn tag(&self) -> u8 { *(self as *const Self a...
#[repr(u8)] enum FieldlessEnum { Unit = 3, Tuple() = 2, Struct {} = 1, } fn main() { const UNIT: Enum = Enum::Unit; const TUPLE: Enum = Enum::Tuple(5); const STRUCT: Enum = Enum::Struct{a: 7, b: 11}; // Ensure discriminants are correct during runtime execution assert_eq!(3, unsafe { bl...
} } #[allow(dead_code)]
random_line_split
iterators.rs
use crate::writers::SSTableDataWriter; use std::boxed::Box; use std::collections::HashMap; pub trait SSTableIterator<'a, K: 'a + SSTableDataWriter, V: 'a + SSTableDataWriter> { fn iter(&'a self) -> Box<dyn Iterator<Item = (&'a K, &'a V)> + 'a>; fn sorted_keys(&'a self) -> Vec<&'a K>; fn get(&'a self, k: &'...
fn sorted_keys(&'a self) -> Vec<&'a K> { let mut keys: Vec<&'a K> = self.keys().collect(); keys.sort_by(|a, b| (*a).cmp(*b)); keys } fn get(&'a self, k: &'a K) -> Option<&'a V> { self.get(k) } }
{ Box::new(self.iter()) }
identifier_body
iterators.rs
use crate::writers::SSTableDataWriter; use std::boxed::Box; use std::collections::HashMap; pub trait SSTableIterator<'a, K: 'a + SSTableDataWriter, V: 'a + SSTableDataWriter> { fn iter(&'a self) -> Box<dyn Iterator<Item = (&'a K, &'a V)> + 'a>; fn sorted_keys(&'a self) -> Vec<&'a K>; fn get(&'a self, k: &'...
(&'a self, k: &'a K) -> Option<&'a V> { self.get(k) } }
get
identifier_name
iterators.rs
use crate::writers::SSTableDataWriter; use std::boxed::Box; use std::collections::HashMap; pub trait SSTableIterator<'a, K: 'a + SSTableDataWriter, V: 'a + SSTableDataWriter> { fn iter(&'a self) -> Box<dyn Iterator<Item = (&'a K, &'a V)> + 'a>; fn sorted_keys(&'a self) -> Vec<&'a K>; fn get(&'a self, k: &'...
keys.sort_by(|a, b| (*a).cmp(*b)); keys } fn get(&'a self, k: &'a K) -> Option<&'a V> { self.get(k) } }
} fn sorted_keys(&'a self) -> Vec<&'a K> { let mut keys: Vec<&'a K> = self.keys().collect();
random_line_split
unique-containing-tag.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 ...
{ t1(int), t2(int), } let _x = box t::t1(10); /*alt *x { t1(a) { assert_eq!(a, 10); } _ { panic!(); } }*/ /*alt x { box t1(a) { assert_eq!(a, 10); } _ { panic!(); } }*/ }
t
identifier_name
unique-containing-tag.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 ...
{ enum t { t1(int), t2(int), } let _x = box t::t1(10); /*alt *x { t1(a) { assert_eq!(a, 10); } _ { panic!(); } }*/ /*alt x { box t1(a) { assert_eq!(a, 10); } _ { panic!(); } }*/ }
identifier_body
unique-containing-tag.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
pub fn main() { enum t { t1(int), t2(int), } let _x = box t::t1(10); /*alt *x { t1(a) { assert_eq!(a, 10); } _ { panic!(); } }*/ /*alt x { box t1(a) { assert_eq!(a, 10); } _ { panic!(); } }*/ }
#![allow(unknown_features)] #![feature(box_syntax)]
random_line_split
lib.rs
/* Copyright (c) 2016 Saurav Sachidanand 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, distribu...
(gpa: u64, size: usize) -> Error { match_error_code(unsafe { hv_vm_unmap(gpa as hv_gpaddr_t, size as size_t) }) } /// Modifies the permissions of a region in the guest physical address space of the virtual /// machine pub fn protect_mem(gpa: u64, size: usize, mem_perm: &MemPerm) -> Error { match_er...
unmap_mem
identifier_name
lib.rs
/* Copyright (c) 2016 Saurav Sachidanand 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, distribu...
match_error_code(unsafe { hv_vcpu_destroy(self.id as hv_vcpuid_t) }) } /// Executes the vCPU pub fn run(&self) -> Error { match_error_code(unsafe { hv_vcpu_run(self.id as hv_vcpuid_t) }) } /// Forces an immediate VMEXIT of the vCPU pub fn...
random_line_split
lib.rs
/* Copyright (c) 2016 Saurav Sachidanand 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, distribu...
/// Reads the current architectural x86 floating point and SIMD state of the vCPU pub fn read_fpstate(&self, buffer: &mut [u8]) -> Error { match_error_code(unsafe { hv_vcpu_read_fpstate(self.id as hv_vcpuid_t, buffer.as_mut_ptr() as *mut c_void, buffer.len() as size_t) ...
{ match_error_code(unsafe { hv_vmx_vcpu_set_apic_address(self.id as hv_vcpuid_t, gpa as uint64_t) }) }
identifier_body
trait-inheritance-num5.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
use std::cmp::Eq; use std::num::NumCast; pub trait NumExt: Eq + Num + NumCast {} impl NumExt for f32 {} impl NumExt for int {} fn num_eq_one<T:NumExt>() -> T { NumCast::from(1).unwrap() } pub fn main() { num_eq_one::<int>(); // you need to actually use the function to trigger the ICE }
// <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.
random_line_split
trait-inheritance-num5.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 ...
{ num_eq_one::<int>(); // you need to actually use the function to trigger the ICE }
identifier_body
trait-inheritance-num5.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 ...
<T:NumExt>() -> T { NumCast::from(1).unwrap() } pub fn main() { num_eq_one::<int>(); // you need to actually use the function to trigger the ICE }
num_eq_one
identifier_name
lib.rs
extern crate piston_truetype; use std::ptr::{null_mut}; use piston_truetype::*; fn expect_glyph(letter: char, expected: String) { unsafe { let bs = include_bytes!("Tuffy_Bold.ttf"); let s = 20.0; let mut w = 0; let mut h = 0; let offset = get_font_offset_for_index(bs.as_p...
panic!("The `A` is malformed.\n\n\nExpected:\n{}|\n\nGot:\n{}|", result, expected); } } } #[test] fn draw_capital_a() { expect_glyph('A', String::new() + " VMM \n" + " @@@i \n" + " i@@@M \n" + " M@o@@. \n" + " .@@.V@o \n" + ...
println!("\n{:?}", expected); println!("{:?}", result);
random_line_split
lib.rs
extern crate piston_truetype; use std::ptr::{null_mut}; use piston_truetype::*; fn expect_glyph(letter: char, expected: String) { unsafe { let bs = include_bytes!("Tuffy_Bold.ttf"); let s = 20.0; let mut w = 0; let mut h = 0; let offset = get_font_offset_for_index(bs.as_p...
() { expect_glyph('A', String::new() + " VMM \n" + " @@@i \n" + " i@@@M \n" + " M@o@@. \n" + " .@@.V@o \n" + " o@M i@@ \n" + " M@i.@@. \n" + ".@@@@@@@o \n" + " o@@@@@@@@ \n" + " @@o .@@: \n" + ":@...
draw_capital_a
identifier_name
lib.rs
extern crate piston_truetype; use std::ptr::{null_mut}; use piston_truetype::*; fn expect_glyph(letter: char, expected: String) { unsafe { let bs = include_bytes!("Tuffy_Bold.ttf"); let s = 20.0; let mut w = 0; let mut h = 0; let offset = get_font_offset_for_index(bs.as_p...
#[test] fn draw_capital_g() { expect_glyph('G', String::new() + " . \n" + " o@@@V. \n" + " M@@M@@@ \n" + " i@@: Vo. \n" + " @@o \n" + ".@@. \n" + ".@@ .oooo:\n" + ".@@ .@@@@i\n" + " @@: iiM@i\n" + " M@o @@...
{ expect_glyph('A', String::new() + " VMM \n" + " @@@i \n" + " i@@@M \n" + " M@o@@. \n" + " .@@.V@o \n" + " o@M i@@ \n" + " M@i .@@. \n" + " .@@@@@@@o \n" + " o@@@@@@@@ \n" + " @@o .@@: \n" + ":...
identifier_body
lib.rs
extern crate piston_truetype; use std::ptr::{null_mut}; use piston_truetype::*; fn expect_glyph(letter: char, expected: String) { unsafe { let bs = include_bytes!("Tuffy_Bold.ttf"); let s = 20.0; let mut w = 0; let mut h = 0; let offset = get_font_offset_for_index(bs.as_p...
} } #[test] fn draw_capital_a() { expect_glyph('A', String::new() + " VMM \n" + " @@@i \n" + " i@@@M \n" + " M@o@@. \n" + " .@@.V@o \n" + " o@M i@@ \n" + " M@i.@@. \n" + ".@@@@@@@o \n" + " o@@@@@@@@ \n" + ...
{ println!("\n{:?}", expected); println!("{:?}", result); panic!("The `A` is malformed.\n\n\nExpected:\n{}|\n\nGot:\n{}|", result, expected); }
conditional_block
parallel.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/. */ //! Implements parallel traversal over the DOM tree. //! //! This traversal is based on Rayon, and therefore its s...
let tls = ScopedTLS::<D::ThreadLocalContext>::new(queue); let root = root.as_node().opaque(); queue.install(|| { rayon::scope(|scope| { traverse_nodes(nodes, root, traversal_data, scope, traversal, &tls); }); }); // Dump statistics to stdout if requested. if Travers...
{ // Handle Gecko's eager initial styling. We don't currently support it // in conjunction with bottom-up traversal. If we did, we'd need to put // it on the context to make it available to the bottom-up phase. let (nodes, depth) = if token.traverse_unstyled_children_only() { debug_assert!(!D::n...
identifier_body
parallel.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/. */ //! Implements parallel traversal over the DOM tree. //! //! This traversal is based on Rayon, and therefore its s...
} } } if let Some(ref mut depth) = traversal_data.current_dom_depth { *depth += 1; } traverse_nodes(discovered_child_nodes, root, traversal_data, scope, traversal, tls); } fn traverse_nodes<'a,'scope, E, D>(nodes: Vec<SendNode<E::ConcreteNode>>, root: OpaqueNode, ...
{ // Otherwise record the number of children to process when the // time comes. node.as_element().unwrap().store_children_to_process(children_to_process); }
conditional_block
parallel.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/. */ //! Implements parallel traversal over the DOM tree. //! //! This traversal is based on Rayon, and therefore its s...
if node.opaque() == root { break; } let parent = match node.parent_element() { None => unreachable!("How can this happen after the break above?"), Some(parent) => parent, }; let remaining = parent.did_process_child(); if remaining!= 0...
// Perform the appropriate operation. traversal.process_postorder(thread_local, node);
random_line_split
parallel.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/. */ //! Implements parallel traversal over the DOM tree. //! //! This traversal is based on Rayon, and therefore its s...
<'a,'scope, E, D>(nodes: Vec<SendNode<E::ConcreteNode>>, root: OpaqueNode, traversal_data: PerLevelTraversalData, scope: &'a rayon::Scope<'scope>, traversal: &'scope D, tls: &'...
traverse_nodes
identifier_name
lib.rs
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option. This file may not be copied, modified, or distributed // except according to those terms. // // Simple Prometheus suppo...
{ cache: Arc<RwLock<LruCache<i64, promo_proto::MetricFamily>>>, host_and_port: &'static str, } impl PrometheusReporter { pub fn new(host_and_port: &'static str) -> Self { PrometheusReporter { // TODO make it configurable cache: Arc::new(RwLock::new(LruCache::new(86400))), ...
PrometheusReporter
identifier_name
lib.rs
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option. This file may not be copied, modified, or distributed // except according to those terms. // // Simple Prometheus suppo...
use protobuf::Message; use std::sync::{Arc, RwLock}; use std::thread; // http handler storage #[derive(Copy, Clone)] struct HandlerStorage; // refer to https://prometheus.io/docs/instrumenting/exposition_formats/ const CONTENT_TYPE: &'static str = "application/vnd.google.protobuf; \ ...
use router::Router; use iron::typemap::Key; use iron::prelude::*; use iron::status; use lru_cache::LruCache;
random_line_split
lib.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...
<T>(&mut self, values: &mut [T]) { let mut i = values.len(); while i >= 2 { // invariant: elements with index >= i have been locked in place. i -= 1; // lock element i in place. values.swap(i, self.gen_range(0, i + 1)); } } } /// Iterator whic...
shuffle
identifier_name
lib.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...
z: seed[2], w: seed[3] } } } impl Rand for XorShiftRng { fn rand<R: Rng>(rng: &mut R) -> XorShiftRng { let mut tuple: (u32, u32, u32, u32) = rng.gen(); while tuple == (0, 0, 0, 0) { tuple = rng.gen(); } let (x, y, z, w) = tuple; ...
random_line_split
lib.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
} /// Shuffle a mutable slice in place. fn shuffle<T>(&mut self, values: &mut [T]) { let mut i = values.len(); while i >= 2 { // invariant: elements with index >= i have been locked in place. i -= 1; // lock element i in place. values.swap(i,...
{ Some(&values[self.gen_range(0, values.len())]) }
conditional_block
lib.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...
/// Return a bool with a 1 in n chance of true fn gen_weighted_bool(&mut self, n: usize) -> bool { n <= 1 || self.gen_range(0, n) == 0 } /// Return an iterator of random characters from the set A-Z,a-z,0-9. fn gen_ascii_chars<'a>(&'a mut self) -> AsciiGenerator<'a, Self> { AsciiGe...
{ assert!(low < high, "Rng.gen_range called with low >= high"); Range::new(low, high).ind_sample(self) }
identifier_body
rust_base64.rs
use indy_api_types::errors::prelude::*; use failure::ResultExt; pub fn encode(doc: &[u8]) -> String { base64::encode(doc) } pub fn decode(doc: &str) -> Result<Vec<u8>, IndyError> { base64::decode(doc) .context("Invalid base64 sequence") .context(IndyErrorKind::InvalidStructure) .map_err(|...
#[test] fn encode_urlsafe_works() { let result = encode_urlsafe(&[1, 2, 3]); assert_eq!("AQID", &result); } #[test] fn decode_urlsafe_works() { let result = decode_urlsafe("AQID"); assert!(result.is_ok(), "Got error"); assert_eq!(&[1, 2, 3], &result.unwrap...
{ let result = decode("AQID"); assert!(result.is_ok(), "Got error"); assert_eq!(&[1, 2, 3], &result.unwrap()[..]); }
identifier_body
rust_base64.rs
use indy_api_types::errors::prelude::*; use failure::ResultExt; pub fn encode(doc: &[u8]) -> String { base64::encode(doc) } pub fn decode(doc: &str) -> Result<Vec<u8>, IndyError> { base64::decode(doc) .context("Invalid base64 sequence") .context(IndyErrorKind::InvalidStructure)
pub fn encode_urlsafe(doc: &[u8]) -> String { base64::encode_config(doc, base64::URL_SAFE) //TODO switch to URL_SAFE_NO_PAD } pub fn decode_urlsafe(doc: &str) -> Result<Vec<u8>, IndyError> { base64::decode_config(doc, base64::URL_SAFE_NO_PAD) .context("Invalid base64URL_SAFE sequence") .context(...
.map_err(|err| err.into()) }
random_line_split
rust_base64.rs
use indy_api_types::errors::prelude::*; use failure::ResultExt; pub fn encode(doc: &[u8]) -> String { base64::encode(doc) } pub fn decode(doc: &str) -> Result<Vec<u8>, IndyError> { base64::decode(doc) .context("Invalid base64 sequence") .context(IndyErrorKind::InvalidStructure) .map_err(|...
(doc: &[u8]) -> String { base64::encode_config(doc, base64::URL_SAFE) //TODO switch to URL_SAFE_NO_PAD } pub fn decode_urlsafe(doc: &str) -> Result<Vec<u8>, IndyError> { base64::decode_config(doc, base64::URL_SAFE_NO_PAD) .context("Invalid base64URL_SAFE sequence") .context(IndyErrorKind::Invalid...
encode_urlsafe
identifier_name
platform.rs
use crate::{error::ParseError, Database}; use cfg_if::cfg_if; use std::{convert::TryFrom, ops::Deref}; use url::Url; cfg_if! {if #[cfg(feature = "with-postgres")]{ use crate::pg::PostgresDB; }} cfg_if! {if #[cfg(feature = "with-sqlite")]{ use crate::sqlite::SqliteDB; }} cfg_if! {if #[cfg(feature = "with-mysq...
(&mut self) -> &mut Self::Target { match *self { #[cfg(feature = "with-postgres")] DBPlatform::Postgres(ref mut pg) => pg.deref_mut(), #[cfg(feature = "with-sqlite")] DBPlatform::Sqlite(ref mut sq) => sq.deref_mut(), #[cfg(feature = "with-mysql")] ...
deref_mut
identifier_name
platform.rs
use crate::{error::ParseError, Database}; use cfg_if::cfg_if; use std::{convert::TryFrom, ops::Deref}; use url::Url; cfg_if! {if #[cfg(feature = "with-postgres")]{ use crate::pg::PostgresDB; }} cfg_if! {if #[cfg(feature = "with-sqlite")]{ use crate::sqlite::SqliteDB; }} cfg_if! {if #[cfg(feature = "with-mysq...
} pub(crate) enum Platform { #[cfg(feature = "with-postgres")] Postgres, #[cfg(feature = "with-sqlite")] Sqlite(String), #[cfg(feature = "with-mysql")] Mysql, Unsupported(String), } impl<'a> TryFrom<&'a str> for Platform { type Error = ParseError; fn try_from(s: &'a str) -> Resul...
{ match *self { #[cfg(feature = "with-postgres")] DBPlatform::Postgres(ref mut pg) => pg.deref_mut(), #[cfg(feature = "with-sqlite")] DBPlatform::Sqlite(ref mut sq) => sq.deref_mut(), #[cfg(feature = "with-mysql")] DBPlatform::Mysql(ref mut...
identifier_body
platform.rs
use crate::{error::ParseError, Database}; use cfg_if::cfg_if;
use crate::pg::PostgresDB; }} cfg_if! {if #[cfg(feature = "with-sqlite")]{ use crate::sqlite::SqliteDB; }} cfg_if! {if #[cfg(feature = "with-mysql")]{ use crate::my::MysqlDB; }} pub enum DBPlatform { #[cfg(feature = "with-postgres")] Postgres(Box<PostgresDB>), #[cfg(feature = "with-sqlite")] ...
use std::{convert::TryFrom, ops::Deref}; use url::Url; cfg_if! {if #[cfg(feature = "with-postgres")]{
random_line_split
issue-2216.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 ...
'quux: loop { if 1 == 2 { break 'foo; } else { break 'bar; } } continue 'foo; } x = 42; break; } println!("{:?}", x); assert_eq!(x, 42); }
'foo: loop { 'bar: loop {
random_line_split
issue-2216.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!(x, 42); }
{ let mut x = 0; 'foo: loop { 'bar: loop { 'quux: loop { if 1 == 2 { break 'foo; } else { break 'bar; } } continue 'foo; } x = 42; break; ...
identifier_body
issue-2216.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 ...
else { break 'bar; } } continue 'foo; } x = 42; break; } println!("{:?}", x); assert_eq!(x, 42); }
{ break 'foo; }
conditional_block
issue-2216.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
() { let mut x = 0; 'foo: loop { 'bar: loop { 'quux: loop { if 1 == 2 { break 'foo; } else { break 'bar; } } continue 'foo; } x = 42; break...
main
identifier_name
dns_sd.rs
// Copyright 2015-2018 Benjamin Fry <benjaminfry@me.com> // // Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or // http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or // http://opensource.org/licenses/MIT>, at your option. This file may not be // copied, modified, or distributed...
fn service_info(&self, name: Name) -> ServiceInfoFuture { let this = self.clone(); let ptr_future = async move { this.txt_lookup(name).await }; ServiceInfoFuture(Box::pin(ptr_future)) } } /// A DNS Service Discovery future of Services discovered through the list operation pub struct...
{ let this = self.clone(); let ptr_future = async move { let options = DnsRequestOptions { expects_multiple_responses: true, }; this.inner_lookup(name, RecordType::PTR, options).await }; ListServicesFuture(Box::pin(ptr_future)) }
identifier_body
dns_sd.rs
// Copyright 2015-2018 Benjamin Fry <benjaminfry@me.com> // // Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or // http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or // http://opensource.org/licenses/MIT>, at your option. This file may not be // copied, modified, or distributed...
/// https://tools.ietf.org/html/rfc6763#section-6 fn service_info(&self, name: Name) -> ServiceInfoFuture; } impl<C: DnsHandle, P: ConnectionProvider<Conn = C>> DnsSdHandle for AsyncResolver<C, P> { fn list_services(&self, name: Name) -> ListServicesFuture { let this = self.clone(); let pt...
/// For registered service types, see: https://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.xhtml fn list_services(&self, name: Name) -> ListServicesFuture; /// Retrieve service information ///
random_line_split