file_name
large_stringlengths
4
69
prefix
large_stringlengths
0
26.7k
suffix
large_stringlengths
0
24.8k
middle
large_stringlengths
0
2.12k
fim_type
large_stringclasses
4 values
main.rs
//! Demonstrates the use of service accounts and the Google Cloud Pubsub API. //! //! Run this binary as.../service_account pub 'your message' in order to publish messages, //! and as.../service_account sub in order to subscribe to those messages. This will look like the //! following: //! //! ``` //! $ target/debug/se...
println!("message <{}> '{}' at {}", message.message_id.unwrap_or(String::new()), String::from_utf8(base64::decode(&message.data .unwrap_or(String::new())) .unwrap()) ...
{ check_or_create_subscription(&methods); let request = pubsub::PullRequest { return_immediately: Some(false), max_messages: Some(1), }; loop { let result = methods.subscriptions_pull(request.clone(), SUBSCRIPTION_NAME).doit(); match result { Err(e) => { ...
identifier_body
main.rs
//! Demonstrates the use of service accounts and the Google Cloud Pubsub API. //! //! Run this binary as.../service_account pub 'your message' in order to publish messages, //! and as.../service_account sub in order to subscribe to those messages. This will look like the //! following: //! //! ``` //! $ target/debug/se...
let result = methods.subscriptions_pull(request.clone(), SUBSCRIPTION_NAME).doit(); match result { Err(e) => { println!("Pull error: {}", e); } Ok((_response, pullresponse)) => { for msg in pullresponse.received_messages.unwrap_or(Vec:...
loop {
random_line_split
main.rs
//! Demonstrates the use of service accounts and the Google Cloud Pubsub API. //! //! Run this binary as.../service_account pub 'your message' in order to publish messages, //! and as.../service_account sub in order to subscribe to those messages. This will look like the //! following: //! //! ``` //! $ target/debug/se...
(methods: &PubsubMethods) -> Topic { let result = methods.topics_get(TOPIC_NAME).doit(); if result.is_err() { println!("Assuming topic doesn't exist; creating topic"); let topic = pubsub::Topic { name: Some(TOPIC_NAME.to_string()) }; let result = methods.topics_create(topic, TOPIC_NAME)...
check_or_create_topic
identifier_name
sync_reqwest.rs
use crate::http::{RobotsTxtClient, DEFAULT_USER_AGENT}; use crate::model::FetchedRobotsTxt; use crate::model::{Error, ErrorKind}; use crate::parser::{parse_fetched_robots_txt, ParseResult}; use reqwest::blocking::{Client, Request}; use reqwest::header::HeaderValue; use reqwest::header::USER_AGENT; use reqwest::Method; ...
}
{ let url = format!("{}/robots.txt", origin.unicode_serialization()); let url = Url::parse(&url).map_err(|err| Error { kind: ErrorKind::Url(err), })?; let mut request = Request::new(Method::GET, url); let _ = request .headers_mut() .insert(USER...
identifier_body
sync_reqwest.rs
use crate::http::{RobotsTxtClient, DEFAULT_USER_AGENT}; use crate::model::FetchedRobotsTxt; use crate::model::{Error, ErrorKind}; use crate::parser::{parse_fetched_robots_txt, ParseResult}; use reqwest::blocking::{Client, Request}; use reqwest::header::HeaderValue; use reqwest::header::USER_AGENT; use reqwest::Method; ...
fn fetch_robots_txt(&self, origin: Origin) -> Self::Result { let url = format!("{}/robots.txt", origin.unicode_serialization()); let url = Url::parse(&url).map_err(|err| Error { kind: ErrorKind::Url(err), })?; let mut request = Request::new(Method::GET, url); let ...
impl RobotsTxtClient for Client { type Result = Result<ParseResult<FetchedRobotsTxt>, Error>;
random_line_split
sync_reqwest.rs
use crate::http::{RobotsTxtClient, DEFAULT_USER_AGENT}; use crate::model::FetchedRobotsTxt; use crate::model::{Error, ErrorKind}; use crate::parser::{parse_fetched_robots_txt, ParseResult}; use reqwest::blocking::{Client, Request}; use reqwest::header::HeaderValue; use reqwest::header::USER_AGENT; use reqwest::Method; ...
(&self, origin: Origin) -> Self::Result { let url = format!("{}/robots.txt", origin.unicode_serialization()); let url = Url::parse(&url).map_err(|err| Error { kind: ErrorKind::Url(err), })?; let mut request = Request::new(Method::GET, url); let _ = request ...
fetch_robots_txt
identifier_name
resource_task.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/. */ //! A task that takes a URL and streams back the binary data. use about_loader; use data_loader; use file_loader;...
let supplied_type = metadata.content_type.map(|ContentType(Mime(toplevel, sublevel, _))| { (format!("{}", toplevel), format!("{}", sublevel)) }); metadata.content_type = classifier.classify(nosniff, check_for_apache_bug, &supplied_type, ...
{ if let Some(ref raw_content_type) = headers.get_raw("content-type") { if raw_content_type.len() > 0 { let ref last_raw_content_type = raw_content_type[raw_content_type.len() - 1]; check_for_apache_bug = last_raw_content_type == b"text/plain" ...
conditional_block
resource_task.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/. */ //! A task that takes a URL and streams back the binary data. use about_loader; use data_loader; use file_loader;...
pub fn add_hsts_entry(&mut self, entry: HSTSEntry) { self.hsts_list.lock().unwrap().push(entry); } pub fn is_host_sts(&self, host: &str) -> bool { self.hsts_list.lock().unwrap().is_host_secure(host) } fn load(&mut self, mut load_data: LoadData, consumer: LoadConsumer) { l...
{ let header = Header::parse_header(&[cookie_list.into_bytes()]); if let Ok(SetCookie(cookies)) = header { for bare_cookie in cookies { if let Some(cookie) = cookie::Cookie::new_wrapped(bare_cookie, &request, source) { self.cookie_storage.push(cookie, sour...
identifier_body
resource_task.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/. */ //! A task that takes a URL and streams back the binary data. use about_loader; use data_loader; use file_loader;...
pub fn add_hsts_entry(&mut self, entry: HSTSEntry) { self.hsts_list.lock().unwrap().push(entry); } pub fn is_host_sts(&self, host: &str) -> bool { self.hsts_list.lock().unwrap().is_host_secure(host) } fn load(&mut self, mut load_data: LoadData, consumer: LoadConsumer) { lo...
} } }
random_line_split
resource_task.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/. */ //! A task that takes a URL and streams back the binary data. use about_loader; use data_loader; use file_loader;...
(user_agent: String, devtools_chan: Option<Sender<DevtoolsControlMsg>>) -> ResourceTask { let hsts_preload = match preload_hsts_domains() { Some(list) => list, None => HSTSList::new() }; let (setup_chan, setup_port) = ipc::channel().unwrap(); let setup_chan_clon...
new_resource_task
identifier_name
packet_matcher.rs
use netinfo::{ConnToInodeMap, InodeToPidMap, Inode, Pid, Connection, InoutType, TransportType, PacketInfo}; use netinfo::error::*; use std::collections::HashMap; use std::time::{Instant, Duration}; /// Provides the tables for PacketMatcher. #[derive(Debug)] struct PacketMatcherTables { /// Matches a source/destina...
(&mut self) -> Result<()> { self.known_connections = self.known_connections.iter() .filter_map(|(&(tt, c), &old)| { let new = self.tables.map_connection(tt, c); match (old, new) { // Connection used to exist, but not ...
update_known_connections
identifier_name
packet_matcher.rs
use netinfo::{ConnToInodeMap, InodeToPidMap, Inode, Pid, Connection, InoutType, TransportType, PacketInfo}; use netinfo::error::*; use std::collections::HashMap; use std::time::{Instant, Duration}; /// Provides the tables for PacketMatcher. #[derive(Debug)] struct PacketMatcherTables { /// Matches a source/destina...
tables: PacketMatcherTables, /// Store all already-handled connections in HashMap so we can look them up /// without having to refresh the other maps (less cpu intensive/caching) /// /// If the resulting value is None, the connection could not be associated with /// process and it is in most ca...
/// `PacketMatcher` provides a function which allows matching /// source/destination adresses for packet to a process. #[derive(Debug)] pub struct PacketMatcher { /// conn->inode->pid Tables
random_line_split
packet_matcher.rs
use netinfo::{ConnToInodeMap, InodeToPidMap, Inode, Pid, Connection, InoutType, TransportType, PacketInfo}; use netinfo::error::*; use std::collections::HashMap; use std::time::{Instant, Duration}; /// Provides the tables for PacketMatcher. #[derive(Debug)] struct PacketMatcherTables { /// Matches a source/destina...
// in these cases the connection was changed/did not change/was created (_, new) => { Some(((tt, c), new)) } } }) .collect(); Ok(()) } /// Find the process to which a packet belongs. pub fn find_p...
{ None }
conditional_block
appdirs.rs
use std::path::PathBuf; use dirs; /// OS specific path to the application cache directory. pub fn cache(app_name: &str) -> Option<PathBuf> { if app_name.is_empty() { return None; } cache_home().map(|mut dir| { dir.push(app_name); dir }) } /// OS specific path for caches. pub fn cache_home() -> Option<...
None => assert!(false, "Couldn't get homedir!") } } _tests() }
{ dir.push(".cache"); dir.push("blub"); let dir_str = format!("{}", dir.display()); let cache_str = format!("{}", cache("blub").unwrap().display()); assert_eq!(dir_str, cache_str); }
conditional_block
appdirs.rs
use std::path::PathBuf; use dirs; /// OS specific path to the application cache directory. pub fn cache(app_name: &str) -> Option<PathBuf> { if app_name.is_empty() { return None; } cache_home().map(|mut dir| { dir.push(app_name); dir }) } /// OS specific path for caches. pub fn cache_home() -> Option<...
{ #[cfg(unix)] fn _tests() { match dirs::home_dir() { Some(mut dir) => { dir.push(".cache"); dir.push("blub"); let dir_str = format!("{}", dir.display()); let cache_str = format!("{}", cache("blub").unwrap().display()); assert_eq!(dir_s...
identifier_body
appdirs.rs
use std::path::PathBuf; use dirs; /// OS specific path to the application cache directory. pub fn cache(app_name: &str) -> Option<PathBuf> { if app_name.is_empty() { return None; } cache_home().map(|mut dir| { dir.push(app_name); dir }) } /// OS specific path for caches. pub fn cache_home() -> Option<...
() { #[cfg(unix)] fn _tests() { match dirs::home_dir() { Some(mut dir) => { dir.push(".cache"); dir.push("blub"); let dir_str = format!("{}", dir.display()); let cache_str = format!("{}", cache("blub").unwrap().display()); assert_eq!(di...
tests
identifier_name
appdirs.rs
use std::path::PathBuf; use dirs; /// OS specific path to the application cache directory. pub fn cache(app_name: &str) -> Option<PathBuf> { if app_name.is_empty() { return None; } cache_home().map(|mut dir| { dir.push(app_name); dir }) } /// OS specific path for caches. pub fn cache_home() -> Option<...
}) } _cache_home() } #[test] #[cfg(test)] fn tests() { #[cfg(unix)] fn _tests() { match dirs::home_dir() { Some(mut dir) => { dir.push(".cache"); dir.push("blub"); let dir_str = format!("{}", dir.display()); let cache_str = format!("{...
random_line_split
htmldatalistelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLDataListElementBinding; use dom::bindings::codegen::Bindings::HTMLDataLi...
{ htmlelement: HTMLElement } impl HTMLDataListElement { fn new_inherited(local_name: Atom, prefix: Option<DOMString>, document: &Document) -> HTMLDataListElement { HTMLDataListElement { htmlelement: HTMLElement::new_inherited(local_...
HTMLDataListElement
identifier_name
htmldatalistelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLDataListElementBinding; use dom::bindings::codegen::Bindings::HTMLDataLi...
use dom::bindings::js::Root; use dom::bindings::str::DOMString; use dom::document::Document; use dom::element::Element; use dom::htmlcollection::{CollectionFilter, HTMLCollection}; use dom::htmlelement::HTMLElement; use dom::htmloptionelement::HTMLOptionElement; use dom::node::{Node, window_from_node}; use string_cache...
random_line_split
htmldatalistelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLDataListElementBinding; use dom::bindings::codegen::Bindings::HTMLDataLi...
} impl HTMLDataListElementMethods for HTMLDataListElement { // https://html.spec.whatwg.org/multipage/#dom-datalist-options fn Options(&self) -> Root<HTMLCollection> { #[derive(JSTraceable, HeapSizeOf)] struct HTMLDataListOptionsFilter; impl CollectionFilter for HTMLDataListOptionsFilt...
{ Node::reflect_node(box HTMLDataListElement::new_inherited(local_name, prefix, document), document, HTMLDataListElementBinding::Wrap) }
identifier_body
collision_objects_dispatcher.rs
use utils::data::hash_map::HashMap; use utils::data::pair::{Pair, PairTWHash}; use utils::data::uid_remap::{UidRemap, FastKey}; use queries::geometry::Contact; use narrow_phase::{CollisionDispatcher, CollisionAlgorithm, ContactSignal, ContactSignalHandler}; use world::CollisionObject; use math::Point; // FIXME: move t...
} }
{ can_move_ok && groups_ok }
conditional_block
collision_objects_dispatcher.rs
use utils::data::hash_map::HashMap; use utils::data::pair::{Pair, PairTWHash}; use utils::data::uid_remap::{UidRemap, FastKey}; use queries::geometry::Contact; use narrow_phase::{CollisionDispatcher, CollisionAlgorithm, ContactSignal, ContactSignalHandler}; use world::CollisionObject; use math::Point; // FIXME: move t...
(shape_dispatcher: Box<CollisionDispatcher<P, M> +'static>) -> CollisionObjectsDispatcher<P, M, T> { CollisionObjectsDispatcher { signal: ContactSignal::new(), pairs: HashMap::new(PairTWHash::new()), shape_dispatcher: shape_dispatcher } ...
new
identifier_name
collision_objects_dispatcher.rs
use utils::data::hash_map::HashMap; use utils::data::pair::{Pair, PairTWHash}; use utils::data::uid_remap::{UidRemap, FastKey}; use queries::geometry::Contact; use narrow_phase::{CollisionDispatcher, CollisionAlgorithm, ContactSignal, ContactSignalHandler}; use world::CollisionObject; use math::Point; // FIXME: move t...
if let Some(cd) = cd { let _ = self.pairs.insert(key, cd); } } else { // Proximity stopped. match self.pairs.get_and_remove(&key) { Some(detector) => { // Trigger the collision lost signal if there was a ...
}
random_line_split
disallow_re_export_all_in_page.rs
use swc_common::pass::Optional; use swc_ecmascript::ast::ExportAll;
use swc_ecmascript::utils::HANDLER; use swc_ecmascript::visit::{noop_fold_type, Fold}; pub fn disallow_re_export_all_in_page(is_page_file: bool) -> impl Fold { Optional::new( DisallowReExportAllInPage, is_page_file ) } struct DisallowReExportAllInPage; impl Fold for DisallowReExportAllInPage { noop_f...
random_line_split
disallow_re_export_all_in_page.rs
use swc_common::pass::Optional; use swc_ecmascript::ast::ExportAll; use swc_ecmascript::utils::HANDLER; use swc_ecmascript::visit::{noop_fold_type, Fold}; pub fn disallow_re_export_all_in_page(is_page_file: bool) -> impl Fold { Optional::new( DisallowReExportAllInPage, is_page_file ) } struct
; impl Fold for DisallowReExportAllInPage { noop_fold_type!(); fn fold_export_all(&mut self, e: ExportAll) -> ExportAll { HANDLER.with(|handler| { handler .struct_span_err( e.span, "Using `export * from '...'` in a page is disallowed. Please use `export...
DisallowReExportAllInPage
identifier_name
disallow_re_export_all_in_page.rs
use swc_common::pass::Optional; use swc_ecmascript::ast::ExportAll; use swc_ecmascript::utils::HANDLER; use swc_ecmascript::visit::{noop_fold_type, Fold}; pub fn disallow_re_export_all_in_page(is_page_file: bool) -> impl Fold
struct DisallowReExportAllInPage; impl Fold for DisallowReExportAllInPage { noop_fold_type!(); fn fold_export_all(&mut self, e: ExportAll) -> ExportAll { HANDLER.with(|handler| { handler .struct_span_err( e.span, "Using `export * from '...'` in a page...
{ Optional::new( DisallowReExportAllInPage, is_page_file ) }
identifier_body
escape_uri.rs
// Copyright 2019 Google 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in ...
iter: self.iter, state: self.state, needs_escape: EscapeUriAuthority, } } } impl<'a, X: NeedsEscape> Display for EscapeUri<'a, X> { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { self.clone().try_for_each(|c| f.write_char(c)) } } ...
random_line_split
escape_uri.rs
// Copyright 2019 Google 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in ...
; impl NeedsEscape for EscapeUriFragment { fn char_needs_escape(c: char) -> bool { !is_char_uri_fragment(c) } } /// An iterator used to apply URI percent encoding to strings. /// /// It is constructed via the method [`escape_uri()`]. /// See the documentation for [`StrExt`] for more information. /// ///...
EscapeUriFragment
identifier_name
escape_uri.rs
// Copyright 2019 Google 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in ...
} /// Converts this iterator into one that escapes all except unreserved characters. pub fn full(self) -> EscapeUri<'a, EscapeUriFull> { EscapeUri { iter: self.iter, state: self.state, needs_escape: EscapeUriFull, } } /// Converts this iterator ...
{ Cow::from(unsafe { from_utf8_unchecked(self.iter.as_slice()) }) }
conditional_block
server.rs
use super::ResponseInfo; use std::net::SocketAddr; use xml_rpc::{self, rouille, Value}; use super::{Response, ResponseError}; pub struct Server { server: xml_rpc::Server, } impl Default for Server { fn default() -> Self { let mut server = xml_rpc::Server::default();
Server { server } } } impl Server { #[inline] pub fn register_value<T>(&mut self, name: impl Into<String>, msg: &'static str, handler: T) where T: Fn(xml_rpc::Params) -> Response<Value> + Send + Sync +'static, { self.server.register_value(name, move |args| { let ...
server.set_on_missing(on_missing);
random_line_split
server.rs
use super::ResponseInfo; use std::net::SocketAddr; use xml_rpc::{self, rouille, Value}; use super::{Response, ResponseError}; pub struct Server { server: xml_rpc::Server, } impl Default for Server { fn default() -> Self { let mut server = xml_rpc::Server::default(); server.set_on_missing(on_m...
( self, uri: &SocketAddr, ) -> xml_rpc::error::Result< xml_rpc::server::BoundServer< impl Fn(&rouille::Request) -> rouille::Response + Send + Sync +'static, >, > { self.server.bind(uri) } } #[allow(clippy::needless_pass_by_value)] #[inline] fn on_missing(...
bind
identifier_name
server.rs
use super::ResponseInfo; use std::net::SocketAddr; use xml_rpc::{self, rouille, Value}; use super::{Response, ResponseError}; pub struct Server { server: xml_rpc::Server, } impl Default for Server { fn default() -> Self
} impl Server { #[inline] pub fn register_value<T>(&mut self, name: impl Into<String>, msg: &'static str, handler: T) where T: Fn(xml_rpc::Params) -> Response<Value> + Send + Sync +'static, { self.server.register_value(name, move |args| { let response = handler(args); ...
{ let mut server = xml_rpc::Server::default(); server.set_on_missing(on_missing); Server { server } }
identifier_body
content.rs
/** * Flow - Realtime log analyzer * Copyright (C) 2016 Daniel Mircea * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later ve...
(&self, width: i32) { wresize(self.window, WINDOW_HEIGHT, width); wrefresh(self.window); } pub fn height(&self) -> i32 { let mut current_x: i32 = 0; let mut current_y: i32 = 0; getyx(self.window, &mut current_y, &mut current_x); current_y } pub fn calcu...
resize
identifier_name
content.rs
/** * Flow - Realtime log analyzer * Copyright (C) 2016 Daniel Mircea * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later ve...
} }
{ self.attributes.remove(index); }
conditional_block
content.rs
/** * Flow - Realtime log analyzer * Copyright (C) 2016 Daniel Mircea * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later ve...
pub fn remove_attribute(&mut self, attr_id: usize) { let index_option = self.attributes.iter().position(|cur| cur.0 == attr_id); if let Some(index) = index_option { self.attributes.remove(index); } } }
{ State { attributes: vec![], foreground: COLOR_DEFAULT, background: COLOR_DEFAULT, highlighted_line: 0, highlighted_match: 0, } }
identifier_body
content.rs
/** * Flow - Realtime log analyzer * Copyright (C) 2016 Daniel Mircea * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later ve...
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ use std::cell::RefCell; use ncurses::*; use ui::color::CO...
* * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of
random_line_split
output-slot-variants.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 ...
int_rec = ret_int_rec(); // non-initializing int_rec = ret_int_rec(); // non-initializing ext_rec = ret_ext_rec(); // initializing ext_rec = ret_ext_rec(); // non-initializing ext_rec = ret_ext_rec(); // non-initializing ext_mem = ret_ext_mem(); // initializing ext_mem = ret_ext_mem()...
{ let mut int_i: isize; let mut ext_i: Box<isize>; let mut int_rec: A; let mut ext_rec: Box<A>; let mut ext_mem: Abox; let mut ext_ext_mem: Box<Abox>; int_i = ret_int_i(); // initializing int_i = ret_int_i(); // non-initializing int_i = ret_int_i(); // non-initializing ext_i =...
identifier_body
output-slot-variants.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 ...
() -> Box<A> { box A {a: 10, b: 10} } fn ret_ext_mem() -> Abox { Abox {a: box 10, b: box 10} } fn ret_ext_ext_mem() -> Box<Abox> { box Abox{a: box 10, b: box 10} } pub fn main() { let mut int_i: isize; let mut ext_i: Box<isize>; let mut int_rec: A; let mut ext_rec: Box<A>; let mut ext_mem: Abox; ...
ret_ext_rec
identifier_name
output-slot-variants.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 ...
int_i = ret_int_i(); // non-initializing int_i = ret_int_i(); // non-initializing ext_i = ret_ext_i(); // initializing ext_i = ret_ext_i(); // non-initializing ext_i = ret_ext_i(); // non-initializing int_rec = ret_int_rec(); // initializing int_rec = ret_int_rec(); // non-initializing...
let mut ext_ext_mem: Box<Abox>; int_i = ret_int_i(); // initializing
random_line_split
snapshot_service.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or
// Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along ...
// (at your option) any later version.
random_line_split
snapshot_service.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any lat...
fn chunk(&self, _hash: H256) -> Option<Bytes> { None } fn status(&self) -> RestorationStatus { self.status.lock().clone() } fn begin_restore(&self, _manifest: ManifestData) { } fn abort_restore(&self) { } fn restore_state_chunk(&self, _hash: H256, _chunk: Bytes) { } fn restore_block_chunk(&self, _hash: H256, _ch...
{ None }
identifier_body
snapshot_service.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any lat...
(&self) { } fn restore_state_chunk(&self, _hash: H256, _chunk: Bytes) { } fn restore_block_chunk(&self, _hash: H256, _chunk: Bytes) { } }
abort_restore
identifier_name
sjadam_board_tests.rs
use board::sjadam::board::SjadamBoard; use board_game_traits::board::{GameResult, Board}; use pgn_traits::pgn::PgnBoard; use tests::tools; use std::collections::hash_map::DefaultHasher; use std::hash::Hash; use std::hash::Hasher; #[test] fn hash_stays_equal() { let mut board = SjadamBoard::start_board(); let...
() { let mut board = SjadamBoard::start_board(); let mut hasher = DefaultHasher::new(); board.hash(&mut hasher); let start_hash = hasher.finish(); for mv_str in ["c1c3", "c8c6", "c3c1", "c6c8"].iter() { let mv = board.move_from_lan(mv_str).unwrap(); board.do_move(mv); } ha...
repetitions_do_not_preserve_hash
identifier_name
sjadam_board_tests.rs
use board::sjadam::board::SjadamBoard; use board_game_traits::board::{GameResult, Board}; use pgn_traits::pgn::PgnBoard; use tests::tools; use std::collections::hash_map::DefaultHasher; use std::hash::Hash; use std::hash::Hasher; #[test] fn hash_stays_equal() { let mut board = SjadamBoard::start_board(); let...
for mv_str in ["e2e4", "e7e5", "c2e2", "c7e7", "e2c2", "e7c7", "c2e2", "c7e7", "e2c2", "e7c7", "c2e2"].iter() { assert_eq!(board.game_result(), None, "Wrong game result for board:\n{:?}", board); let mv = board.move_from_lan(mv_str).unwrap(); board.do_move(mv); } assert_eq!(board.ga...
// There is no repetition from move 1, because of en passant
random_line_split
sjadam_board_tests.rs
use board::sjadam::board::SjadamBoard; use board_game_traits::board::{GameResult, Board}; use pgn_traits::pgn::PgnBoard; use tests::tools; use std::collections::hash_map::DefaultHasher; use std::hash::Hash; use std::hash::Hasher; #[test] fn hash_stays_equal() { let mut board = SjadamBoard::start_board(); let...
#[test] fn pawn_moves_can_repeat() { let mut board = SjadamBoard::start_board(); // There is no repetition from move 1, because of en passant for mv_str in ["e2e4", "e7e5", "c2e2", "c7e7", "e2c2", "e7c7", "c2e2", "c7e7", "e2c2", "e7c7", "c2e2"].iter() { assert_eq!(board.game_result(), None, "Wron...
{ let mut board = SjadamBoard::start_board(); for mv_str in ["c1c3", "c8c6", "c3c1", "c6c8", "c1c3", "c8c6", "c3c1", "c6c8"].iter() { assert_eq!(board.game_result(), None, "Wrong game result for board:\n{:?}", board); let mv = board.move_from_lan(mv_str).unwrap(); board.do_move(mv); ...
identifier_body
customevent.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::CustomEventBinding; use dom::bindings::codegen::Bindings::CustomEventBinding...
return; } self.detail.set(detail); event.InitEvent(type_, can_bubble, cancelable); } } impl Reflectable for CustomEvent { fn reflector<'a>(&'a self) -> &'a Reflector { self.event.reflector() } }
cancelable: bool, detail: JSVal) { let event: JSRef<Event> = EventCast::from_ref(self); if event.dispatching() {
random_line_split
customevent.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::CustomEventBinding; use dom::bindings::codegen::Bindings::CustomEventBinding...
} impl CustomEvent { fn new_inherited(type_id: EventTypeId) -> CustomEvent { CustomEvent { event: Event::new_inherited(type_id), detail: Cell::new(NullValue()), } } pub fn new_uninitialized(global: GlobalRef) -> Temporary<CustomEvent> { reflect_dom_object(b...
{ *self.type_id() == CustomEventTypeId }
identifier_body
customevent.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::CustomEventBinding; use dom::bindings::codegen::Bindings::CustomEventBinding...
(self, _cx: *mut JSContext, type_: DOMString, can_bubble: bool, cancelable: bool, detail: JSVal) { let event: JSRef<Event> = EventCast::from_ref(self); if event.dispatching() { ...
InitCustomEvent
identifier_name
customevent.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::CustomEventBinding; use dom::bindings::codegen::Bindings::CustomEventBinding...
self.detail.set(detail); event.InitEvent(type_, can_bubble, cancelable); } } impl Reflectable for CustomEvent { fn reflector<'a>(&'a self) -> &'a Reflector { self.event.reflector() } }
{ return; }
conditional_block
missing_enforced_import_rename.rs
use clippy_utils::{diagnostics::span_lint_and_sugg, source::snippet_opt}; use rustc_data_structures::fx::FxHashMap; use rustc_errors::Applicability; use rustc_hir::{def::Res, def_id::DefId, Item, ItemKind, UseKind}; use rustc_lint::{LateContext, LateLintPass, LintContext}; use rustc_session::{declare_tool_lint, impl_l...
/// /// ### Example /// An example clippy.toml configuration: /// ```toml /// # clippy.toml /// enforced-import-renames = [ { path = "serde_json::Value", rename = "JsonValue" }] /// ``` /// /// ```rust,ignore /// use serde_json::Value; /// ``` /// Use instead: /// ```...
/// ### Why is this bad? /// Consistency is important, if a project has defined import /// renames they should be followed. More practically, some item names are too /// vague outside of their defining scope this can enforce a more meaningful naming.
random_line_split
missing_enforced_import_rename.rs
use clippy_utils::{diagnostics::span_lint_and_sugg, source::snippet_opt}; use rustc_data_structures::fx::FxHashMap; use rustc_errors::Applicability; use rustc_hir::{def::Res, def_id::DefId, Item, ItemKind, UseKind}; use rustc_lint::{LateContext, LateLintPass, LintContext}; use rustc_session::{declare_tool_lint, impl_l...
(&mut self, cx: &LateContext<'_>, item: &Item<'_>) { if_chain! { if let ItemKind::Use(path, UseKind::Single) = &item.kind; if let Res::Def(_, id) = path.res; if let Some(name) = self.renames.get(&id); // Remove semicolon since it is not present for nested imports ...
check_item
identifier_name
missing_enforced_import_rename.rs
use clippy_utils::{diagnostics::span_lint_and_sugg, source::snippet_opt}; use rustc_data_structures::fx::FxHashMap; use rustc_errors::Applicability; use rustc_hir::{def::Res, def_id::DefId, Item, ItemKind, UseKind}; use rustc_lint::{LateContext, LateLintPass, LintContext}; use rustc_session::{declare_tool_lint, impl_l...
} } fn check_item(&mut self, cx: &LateContext<'_>, item: &Item<'_>) { if_chain! { if let ItemKind::Use(path, UseKind::Single) = &item.kind; if let Res::Def(_, id) = path.res; if let Some(name) = self.renames.get(&id); // Remove semicolon since it...
{ self.renames.insert(id, Symbol::intern(rename)); }
conditional_block
missing_enforced_import_rename.rs
use clippy_utils::{diagnostics::span_lint_and_sugg, source::snippet_opt}; use rustc_data_structures::fx::FxHashMap; use rustc_errors::Applicability; use rustc_hir::{def::Res, def_id::DefId, Item, ItemKind, UseKind}; use rustc_lint::{LateContext, LateLintPass, LintContext}; use rustc_session::{declare_tool_lint, impl_l...
fn check_item(&mut self, cx: &LateContext<'_>, item: &Item<'_>) { if_chain! { if let ItemKind::Use(path, UseKind::Single) = &item.kind; if let Res::Def(_, id) = path.res; if let Some(name) = self.renames.get(&id); // Remove semicolon since it is not present ...
{ for Rename { path, rename } in &self.conf_renames { if let Res::Def(_, id) = clippy_utils::path_to_res(cx, &path.split("::").collect::<Vec<_>>()) { self.renames.insert(id, Symbol::intern(rename)); } } }
identifier_body
spinner.rs
// This file was generated by gir (https://github.com/gtk-rs/gir) // from gir-files (https://github.com/gtk-rs/gir-files) // DO NOT EDIT use Buildable; use Widget; use ffi; use glib::StaticType; use glib::Value; use glib::object::Cast; use glib::object::IsA; use glib::signal::SignalHandlerId; use glib::signal::connect...
(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Spinner") } }
fmt
identifier_name
spinner.rs
// This file was generated by gir (https://github.com/gtk-rs/gir) // from gir-files (https://github.com/gtk-rs/gir-files) // DO NOT EDIT use Buildable; use Widget; use ffi; use glib::StaticType; use glib::Value; use glib::object::Cast; use glib::object::IsA; use glib::signal::SignalHandlerId; use glib::signal::connect...
} unsafe extern "C" fn notify_active_trampoline<P, F: Fn(&P) +'static>(this: *mut ffi::GtkSpinner, _param_spec: glib_ffi::gpointer, f: glib_ffi::gpointer) where P: IsA<Spinner> { let f: &F = transmute(f); f(&Spinner::from_glib_borrow(this).unsafe_cast()) } impl fmt::Display for Spinner { fn fmt(&self, f:...
{ unsafe { let f: Box_<F> = Box_::new(f); connect_raw(self.as_ptr() as *mut _, b"notify::active\0".as_ptr() as *const _, Some(transmute(notify_active_trampoline::<Self, F> as usize)), Box_::into_raw(f)) } }
identifier_body
spinner.rs
// This file was generated by gir (https://github.com/gtk-rs/gir) // from gir-files (https://github.com/gtk-rs/gir-files) // DO NOT EDIT use Buildable; use Widget; use ffi; use glib::StaticType; use glib::Value; use glib::object::Cast; use glib::object::IsA; use glib::signal::SignalHandlerId; use glib::signal::connect...
} pub const NONE_SPINNER: Option<&Spinner> = None; pub trait SpinnerExt:'static { fn start(&self); fn stop(&self); fn get_property_active(&self) -> bool; fn set_property_active(&self, active: bool); fn connect_property_active_notify<F: Fn(&Self) +'static>(&self, f: F) -> SignalHandlerId; } im...
impl Default for Spinner { fn default() -> Self { Self::new() }
random_line_split
method-argument-inference-associated-type.rs
// Copyright 2017 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 struct ClientMap2; pub trait Service { type Request; fn call(&self, _req: Self::Request); } pub struct S<T>(T); impl Service for ClientMap { type Request = S<Box<Fn(i32)>>; fn call(&self, _req: Self::Request) {} } impl Service for ClientMap2 { type Request = (Box<Fn(i32)>,); fn call(&...
ClientMap
identifier_name
method-argument-inference-associated-type.rs
// Copyright 2017 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 ...
ClientMap.call(S(Box::new(|_msgid| ()))); ClientMap2.call((Box::new(|_msgid| ()),)); }
fn main() { ClientMap.call(S { 0: Box::new(|_msgid| ()) });
random_line_split
2_8_mutual_attraction.rs
// The Nature of Code // Daniel Shiffman // http://natureofcode.com // // Example 2-8: Mutual Attraction use nannou::prelude::*; fn main() { nannou::app(model).update(update).run(); } struct Model { movers: Vec<Mover>, } struct Mover { position: Point2, velocity: Vector2, acceleration: Vector2, ...
self.acceleration += f; } fn update(&mut self) { self.velocity += self.acceleration; self.position += self.velocity; self.acceleration *= 0.0; } fn attract(&self, m: &Mover) -> Vector2 { let mut force = self.position - m.position; // Calculate direction of force...
} } fn apply_force(&mut self, force: Vector2) { let f = force / self.mass;
random_line_split
2_8_mutual_attraction.rs
// The Nature of Code // Daniel Shiffman // http://natureofcode.com // // Example 2-8: Mutual Attraction use nannou::prelude::*; fn main() { nannou::app(model).update(update).run(); } struct Model { movers: Vec<Mover>, } struct Mover { position: Point2, velocity: Vector2, acceleration: Vector2, ...
} m.movers[i].update(); } } fn view(app: &App, m: &Model, frame: Frame) { // Begin drawing let draw = app.draw(); draw.background().color(WHITE); // Draw movers for mover in &m.movers { mover.display(&draw); } // Write the result of our drawing to the window's...
{ let force = m.movers[j].attract(&m.movers[i]); m.movers[i].apply_force(force); }
conditional_block
2_8_mutual_attraction.rs
// The Nature of Code // Daniel Shiffman // http://natureofcode.com // // Example 2-8: Mutual Attraction use nannou::prelude::*; fn main() { nannou::app(model).update(update).run(); } struct Model { movers: Vec<Mover>, } struct Mover { position: Point2, velocity: Vector2, acceleration: Vector2, ...
(app: &App) -> Model { let rect = Rect::from_w_h(640.0, 360.0); app.new_window() .size(rect.w() as u32, rect.h() as u32) .view(view) .build() .unwrap(); let movers = (0..1000) .map(|_| { Mover::new( random_range(0.1f32, 2.0), ra...
model
identifier_name
lib.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! Calculate [specified][specified] and [computed values][computed] from a //! tree of DOM nodes and a set of sty...
pub mod bloom; pub mod cache; pub mod cascade_info; pub mod context; pub mod custom_properties; pub mod data; pub mod dom; pub mod element_state; pub mod error_reporting; pub mod font_face; pub mod font_metrics; #[cfg(feature = "gecko")] #[allow(unsafe_code)] pub mod gecko; #[cfg(feature = "gecko")] #[allow(unsafe_code...
random_line_split
lib.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! Calculate [specified][specified] and [computed values][computed] from a //! tree of DOM nodes and a set of sty...
try!(list[0].to_css(dest)); for item in list.iter().skip(1) { try!(write!(dest, ", ")); try!(item.to_css(dest)); } Ok(()) }
{ return Ok(()); }
conditional_block
lib.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! Calculate [specified][specified] and [computed values][computed] from a //! tree of DOM nodes and a set of sty...
<W, T>(dest: &mut W, list: &[T]) -> fmt::Result where W: fmt::Write, T: ToCss, { if list.is_empty() { return Ok(()); } try!(list[0].to_css(dest)); for item in list.iter().skip(1) { try...
serialize_comma_separated_list
identifier_name
lib.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! Calculate [specified][specified] and [computed values][computed] from a //! tree of DOM nodes and a set of sty...
/// Serializes as CSS a comma-separated list of any `T` that supports being /// serialized as CSS. pub fn serialize_comma_separated_list<W, T>(dest: &mut W, list: &[T]) -> fmt::Result where W: fmt::Write, T: ToCss, {...
{ let a: &T = &**a; let b: &T = &**b; (a as *const T) == (b as *const T) }
identifier_body
htmlmapelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLMapElementBinding; use dom::bindings::js::Root; use dom::bindings::str::...
(localName: Atom, prefix: Option<DOMString>, document: &Document) -> Root<HTMLMapElement> { Node::reflect_node(box HTMLMapElement::new_inherited(localName, prefix, document), document, HTMLMapElementBinding::Wrap) } }
new
identifier_name
htmlmapelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLMapElementBinding; use dom::bindings::js::Root; use dom::bindings::str::...
htmlelement: HTMLElement } impl HTMLMapElement { fn new_inherited(localName: Atom, prefix: Option<DOMString>, document: &Document) -> HTMLMapElement { HTMLMapElement { htmlelement: HTMLElement::new_inherited(localName, prefix, document) } ...
pub struct HTMLMapElement {
random_line_split
mod.rs
// Copyright 2020 Google LLC // // Use of this source code is governed by an MIT-style license that can be found // in the LICENSE file or at https://opensource.org/licenses/MIT. //! Handlers and types for agent's actions. //! //! The basic functionality that a GRR agent exposes is called an _action_. //! Actions are ...
(unit: ()) -> Result<(), session::ParseError> { Ok(unit) } } impl Response for () { const RDF_NAME: Option<&'static str> = None; type Proto = (); fn into_proto(self) { } } /// Dispatches `task` to a handler appropriate for the given `action`. /// /// This method is a mapping between act...
from_proto
identifier_name
mod.rs
// Copyright 2020 Google LLC // // Use of this source code is governed by an MIT-style license that can be found // in the LICENSE file or at https://opensource.org/licenses/MIT. //! Handlers and types for agent's actions. //! //! The basic functionality that a GRR agent exposes is called an _action_. //! Actions are ...
/// A method for converting structured responses into raw proto messages. fn into_proto(self) -> Self::Proto; } impl Request for () { type Proto = (); fn from_proto(unit: ()) -> Result<(), session::ParseError> { Ok(unit) } } impl Response for () { const RDF_NAME: Option<&'static str...
random_line_split
mod.rs
// Copyright 2020 Google LLC // // Use of this source code is governed by an MIT-style license that can be found // in the LICENSE file or at https://opensource.org/licenses/MIT. //! Handlers and types for agent's actions. //! //! The basic functionality that a GRR agent exposes is called an _action_. //! Actions are ...
} impl Response for () { const RDF_NAME: Option<&'static str> = None; type Proto = (); fn into_proto(self) { } } /// Dispatches `task` to a handler appropriate for the given `action`. /// /// This method is a mapping between action names (as specified in the protocol) /// and action handlers (impl...
{ Ok(unit) }
identifier_body
ffi.rs
//! Utilities related to FFI bindings. use vec::Vec; use boxed::Box; #[derive(Clone)] /// Represents an owned C style string /// /// This type generates compatible C-strings from Rust. It guarantees that /// there is no null bytes in the string and that the string is ended by a null /// byte. pub struct CString { ...
pub fn as_bytes_with_nul(&self) -> &[u8] { &*self.data } }
/// Return the raw representation of the string. /// /// This buffer is guaranteed without intermediate null bytes and includes /// the trailing null byte.
random_line_split
ffi.rs
//! Utilities related to FFI bindings. use vec::Vec; use boxed::Box; #[derive(Clone)] /// Represents an owned C style string /// /// This type generates compatible C-strings from Rust. It guarantees that /// there is no null bytes in the string and that the string is ended by a null /// byte. pub struct CString { ...
(&self) -> &[u8] { &*self.data } }
as_bytes_with_nul
identifier_name
ffi.rs
//! Utilities related to FFI bindings. use vec::Vec; use boxed::Box; #[derive(Clone)] /// Represents an owned C style string /// /// This type generates compatible C-strings from Rust. It guarantees that /// there is no null bytes in the string and that the string is ended by a null /// byte. pub struct CString { ...
} v.push(0); Ok(CString { data: v.into_boxed_slice(), }) } /// Return the raw representation of the string without the trailing null /// byte pub fn as_bytes(&self) -> &[u8] { &self.data[..self.data.len() - 1] } /// Return the raw represen...
{ return Err(()); }
conditional_block
cmd.rs
use std; use std::fmt::Display; use std::fmt::Formatter; use std::str::FromStr; #[derive(Debug)] pub enum Error { InvalidCommand(String), TooFewArguments(String, usize, usize), NoCommand, UnknownError(String), } impl Display for Error { fn fmt(&self, f: &mut Formatter) -> std::fmt::Result { match *se...
<S: ToString>(msg: S) -> Error { Error::UnknownError(msg.to_string()) } } type Result<V> = std::result::Result<V, Error>; #[derive(Debug, PartialEq, Eq)] pub enum Command { Init, ListKeys, PutString(String, String), Drop(String), CreateEmptyList(String), PushListValue(String, String), PopListVa...
unknown
identifier_name
cmd.rs
use std; use std::fmt::Display; use std::fmt::Formatter; use std::str::FromStr; #[derive(Debug)] pub enum Error { InvalidCommand(String), TooFewArguments(String, usize, usize), NoCommand, UnknownError(String), } impl Display for Error { fn fmt(&self, f: &mut Formatter) -> std::fmt::Result { match *se...
assert_eq!(cmd, Command::Init); } #[test] fn test_put_string() { let cmd = Command::from_str("put bla gna").unwrap(); assert_eq!(cmd, Command::PutString("bla".to_string(), "gna".to_string())); } #[test] fn test_empty() { let err = Command::from_strings(Vec::new()).err().unwrap(); if...
let cmd = Command::from_str("init").unwrap();
random_line_split
cmd.rs
use std; use std::fmt::Display; use std::fmt::Formatter; use std::str::FromStr; #[derive(Debug)] pub enum Error { InvalidCommand(String), TooFewArguments(String, usize, usize), NoCommand, UnknownError(String), } impl Display for Error { fn fmt(&self, f: &mut Formatter) -> std::fmt::Result { match *se...
} #[test] fn test_put_string_wrong_fmt() { let err = Command::from_str("put bla,gna").err().unwrap(); if let Error::TooFewArguments(_, expected, actual) = err { assert_eq!(expected, 3); assert_eq!(actual, 2); } else { assert!(false); } } #[test] fn test_invalid_command(...
{ assert!(false); }
conditional_block
cmd.rs
use std; use std::fmt::Display; use std::fmt::Formatter; use std::str::FromStr; #[derive(Debug)] pub enum Error { InvalidCommand(String), TooFewArguments(String, usize, usize), NoCommand, UnknownError(String), } impl Display for Error { fn fmt(&self, f: &mut Formatter) -> std::fmt::Result { match *se...
}
{ Command::from_str("invalid test").unwrap(); }
identifier_body
config.rs
extern crate serde; extern crate serde_json; use std::io; use std::io::Read; use std::fs::File; use std::error::Error; include!(concat!(env!("OUT_DIR"), "/config.rs")); #[derive(Debug)] pub struct
{ pub file_path: String, pub auth: String, } impl Config { pub fn load_from_file(path: &str) -> Result<Config, io::Error> { // TEST SECTION let point = ConfigFile { file_path: "data".to_string(), auth_file: "auth_file".to_string() }; let serialized = serde_json::to_string(&point).u...
Config
identifier_name
config.rs
extern crate serde; extern crate serde_json; use std::io; use std::io::Read; use std::fs::File; use std::error::Error; include!(concat!(env!("OUT_DIR"), "/config.rs")); #[derive(Debug)] pub struct Config { pub file_path: String, pub auth: String, } impl Config { pub fn load_from_file(path: &str) -> Resu...
let mut auth_file = try!(File::open(deserialized.auth_file)); let mut auth_code = String::new(); try!(auth_file.read_to_string(& mut auth_code)); Ok(Config { file_path: deserialized.file_path, auth: auth_code, }) } }
{ // TEST SECTION let point = ConfigFile { file_path: "data".to_string(), auth_file: "auth_file".to_string() }; let serialized = serde_json::to_string(&point).unwrap(); println!("{}", serialized); let deserialized: ConfigFile = serde_json::from_str(&serialized).unwrap(); ...
identifier_body
config.rs
extern crate serde; extern crate serde_json;
use std::io; use std::io::Read; use std::fs::File; use std::error::Error; include!(concat!(env!("OUT_DIR"), "/config.rs")); #[derive(Debug)] pub struct Config { pub file_path: String, pub auth: String, } impl Config { pub fn load_from_file(path: &str) -> Result<Config, io::Error> { // TEST SECTI...
random_line_split
list-pokemon.rs
use rgen3_save::{Pokemon, SaveSections}; use rgen3_string::decode_string; use std::collections::HashMap; macro_rules! make_poke_map { ($($id:literal,$name:literal,$($kind:literal,)+;)+) => {{ let mut map = HashMap::new(); $( let mut kinds = Vec::new(); $( kin...
println!("hp: {}", evc.hp); println!("atk: {}", evc.attack); println!("def: {}", evc.defense); println!("spd: {}", evc.speed); println!("sp atk: {}", evc.sp_attack); println!("sp def: {}", evc.sp_defense); println!( "total: {}/510", u16::from(evc.hp) + u16::from(e...
{ let unk_string: String; let unk_vec = vec![""]; let (name, kinds) = match pokemap.get(&pokemon.data.growth.species) { Some((name, kinds)) => (*name, kinds), None => { unk_string = format!("<Unknown> ({})", pokemon.data.growth.species); (&unk_string[..], &unk_vec) ...
identifier_body
list-pokemon.rs
use rgen3_save::{Pokemon, SaveSections}; use rgen3_string::decode_string; use std::collections::HashMap; macro_rules! make_poke_map { ($($id:literal,$name:literal,$($kind:literal,)+;)+) => {{ let mut map = HashMap::new(); $( let mut kinds = Vec::new(); $( kin...
map.insert($id, ($name, kinds)); );+ map }} } #[allow(clippy::zero_prefixed_literal)] fn main() { let mut args = std::env::args().skip(1); let path = args.next().expect("Need path to save as first arg"); let save = rgen3_save::Save::load_from_file(&path).unwrap(); let Sa...
)+
random_line_split
list-pokemon.rs
use rgen3_save::{Pokemon, SaveSections}; use rgen3_string::decode_string; use std::collections::HashMap; macro_rules! make_poke_map { ($($id:literal,$name:literal,$($kind:literal,)+;)+) => {{ let mut map = HashMap::new(); $( let mut kinds = Vec::new(); $( kin...
() { let mut args = std::env::args().skip(1); let path = args.next().expect("Need path to save as first arg"); let save = rgen3_save::Save::load_from_file(&path).unwrap(); let SaveSections { team, pc_boxes,.. } = save.sections(); let pokemap = include!("../../poke.incl"); println!("== Team ==");...
main
identifier_name
list.rs
use anyhow::Result; use clap::{App, Arg, ArgMatches}; use rhq::Workspace; use std::str::FromStr; #[derive(Debug)] enum ListFormat { Name, FullPath, } impl FromStr for ListFormat { type Err = (); fn from_str(s: &str) -> Result<Self, Self::Err> { match s { "name" => Ok(ListFormat::N...
<'a, 'b: 'a>(app: App<'a, 'b>) -> App<'a, 'b> { app.about("List local repositories managed by rhq").arg( Arg::from_usage("--format=[format] 'List format'") .possible_values(&["name", "fullpath"]) .default_value("fullpath"), ) } pub fn from_matches(m: &A...
app
identifier_name
list.rs
use anyhow::Result; use clap::{App, Arg, ArgMatches}; use rhq::Workspace; use std::str::FromStr; #[derive(Debug)] enum ListFormat { Name, FullPath, } impl FromStr for ListFormat { type Err = (); fn from_str(s: &str) -> Result<Self, Self::Err> { match s { "name" => Ok(ListFormat::N...
ListFormat::FullPath => println!("{}", repo.path_string()), } Ok(()) }) } }
pub fn run(self) -> Result<()> { let workspace = Workspace::new()?; workspace.for_each_repo(|repo| { match self.format { ListFormat::Name => println!("{}", repo.name()),
random_line_split
list.rs
use anyhow::Result; use clap::{App, Arg, ArgMatches}; use rhq::Workspace; use std::str::FromStr; #[derive(Debug)] enum ListFormat { Name, FullPath, } impl FromStr for ListFormat { type Err = (); fn from_str(s: &str) -> Result<Self, Self::Err> { match s { "name" => Ok(ListFormat::N...
}
{ let workspace = Workspace::new()?; workspace.for_each_repo(|repo| { match self.format { ListFormat::Name => println!("{}", repo.name()), ListFormat::FullPath => println!("{}", repo.path_string()), } Ok(()) }) }
identifier_body
output.rs
// Copyright © 2008-2011 Kristian Høgsberg // Copyright © 2010-2011 Intel Corporation // Copyright © 2012-2013 Collabora, Ltd. // // Permission to use, copy, modify, distribute, and sell this // software and its documentation for any purpose is hereby granted // without fee, provided that the above copyright notice ap...
fn from_i32(num: i32) -> Option<Self> { return Self::from_u32(num as u32); } } pub trait OutputTransformSet { fn has_normal(&self) -> bool; fn has_90(&self) -> bool; fn has_180(&self) -> bool; fn has_270(&self) -> bool; fn has_flipped(&self) -> bool; fn has_flipped_90(&self) -> bo...
return match num { 0 => Some(OutputTransform::Normal), 1 => Some(OutputTransform::_90), 2 => Some(OutputTransform::_180), 3 => Some(OutputTransform::_270), 4 => Some(OutputTransform::Flipped), 5 => Some(OutputTransform::Flipped90), ...
identifier_body
output.rs
// Copyright © 2008-2011 Kristian Høgsberg // Copyright © 2010-2011 Intel Corporation // Copyright © 2012-2013 Collabora, Ltd. // // Permission to use, copy, modify, distribute, and sell this // software and its documentation for any purpose is hereby granted // without fee, provided that the above copyright notice ap...
// purpose. It is provided "as is" without express or implied // warranty. // // THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS // SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND // FITNESS, IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY // SPECIAL, INDIRECT OR CONSEQUE...
random_line_split
output.rs
// Copyright © 2008-2011 Kristian Høgsberg // Copyright © 2010-2011 Intel Corporation // Copyright © 2012-2013 Collabora, Ltd. // // Permission to use, copy, modify, distribute, and sell this // software and its documentation for any purpose is hereby granted // without fee, provided that the above copyright notice ap...
Normal = 0, _90 = 1, _180 = 2, _270 = 3, Flipped = 4, Flipped90 = 5, Flipped180 = 6, Flipped270 = 7, } impl FromPrimitive for OutputTransform { fn from_u32(num: u32) -> Option<Self> { return match num { 0 => Some(OutputTransform::Normal), 1 => Some(Out...
utTransform {
identifier_name
extent.rs
// // Copyright 2016 Andrew Hunter // // 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...
/// The entire subtree (all children, and their children, and so on) /// /// Unlike Children, this covers the current node and its entire subtree SubTree } impl TreeExtent { /// /// Returns true if this extent will cover the specified address, which is relative to where the extent starts /...
/// The children of this node /// /// This does not extend beyond the immediate children of the current node. Children,
random_line_split
extent.rs
// // Copyright 2016 Andrew Hunter // // 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...
() { assert!(TreeExtent::Children.covers(&(1.to_tree_address()))); assert!(TreeExtent::Children.covers(&("tag".to_tree_address()))); assert!(!TreeExtent::Children.covers(&((1, 2).to_tree_address()))); assert!(!TreeExtent::Children.covers(&(("tag", "othertag").to_tree_address()))); ...
children_covers_only_immediate_children
identifier_name
extent.rs
// // Copyright 2016 Andrew Hunter // // 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...
}
{ assert!(TreeExtent::SubTree.covers(&(1.to_tree_address()))); assert!(TreeExtent::SubTree.covers(&("tag".to_tree_address()))); assert!(TreeExtent::SubTree.covers(&((1, 2).to_tree_address()))); assert!(TreeExtent::SubTree.covers(&(("tag", "othertag").to_tree_address()))); assert...
identifier_body
mod.rs
use std::{ collections::{BTreeMap, BTreeSet}, ops::Not, }; use anyhow::Result; use bitflags::bitflags; use crate::{ analysis::{ cfg::{flow::Flow, InstructionIndex, CFG}, pe::{Import, ImportedSymbol}, }, loader::pe::PE, VA, }; pub mod cfg; pub mod formatter; bitflags! { pu...
(&mut self, va: VA, name: String) { self.names_by_address.insert(va, name.clone()); self.addresses_by_name.insert(name, va); } pub fn contains_address(&self, va: VA) -> bool { return self.names_by_address.get(&va).is_some(); } pub fn contains_name(&self, name: &str) -> bool { ...
insert
identifier_name
mod.rs
use std::{ collections::{BTreeMap, BTreeSet}, ops::Not, }; use anyhow::Result; use bitflags::bitflags; use crate::{ analysis::{ cfg::{flow::Flow, InstructionIndex, CFG}, pe::{Import, ImportedSymbol}, }, loader::pe::PE, VA, }; pub mod cfg; pub mod formatter; bitflags! { pu...
} pub fn contains_name(&self, name: &str) -> bool { return self.addresses_by_name.get(name).is_some(); } } pub struct WorkspaceAnalysis { // derived from: // - file format analysis passes // - cfg flow analysis (call insns) // - manual actions pub functions: BTreeMap<VA, ...
self.addresses_by_name.insert(name, va); } pub fn contains_address(&self, va: VA) -> bool { return self.names_by_address.get(&va).is_some();
random_line_split
mod.rs
use std::{ collections::{BTreeMap, BTreeSet}, ops::Not, }; use anyhow::Result; use bitflags::bitflags; use crate::{ analysis::{ cfg::{flow::Flow, InstructionIndex, CFG}, pe::{Import, ImportedSymbol}, }, loader::pe::PE, VA, }; pub mod cfg; pub mod formatter; bitflags! { pu...
} } for name in [ "kernel32.dll!ExitProcess", "kernel32.dll!ExitThread", "exit", "_exit", "__exit", "__amsg_exit", ] { if let Some(&va) = names.addresses_by_name.get(name) { log::inf...
{ // colliding matches, can't determine the name. // TODO: maybe check for special case that all names are the same? log::info!("FLIRT match: {:#x}: {} collisions", function, matches.len()); continue; }
conditional_block
mod.rs
use std::{ collections::{BTreeMap, BTreeSet}, ops::Not, }; use anyhow::Result; use bitflags::bitflags; use crate::{ analysis::{ cfg::{flow::Flow, InstructionIndex, CFG}, pe::{Import, ImportedSymbol}, }, loader::pe::PE, VA, }; pub mod cfg; pub mod formatter; bitflags! { pu...
pub fn contains_address(&self, va: VA) -> bool { return self.names_by_address.get(&va).is_some(); } pub fn contains_name(&self, name: &str) -> bool { return self.addresses_by_name.get(name).is_some(); } } pub struct WorkspaceAnalysis { // derived from: // - file format anal...
{ self.names_by_address.insert(va, name.clone()); self.addresses_by_name.insert(name, va); }
identifier_body
textdecoder.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::TextDecoderBinding; use dom::bindings::codegen::Bindings::TextDecoderBinding...
let mut length = 0; let mut data = ptr::null_mut(); if unsafe { JS_GetObjectAsArrayBufferView(input, &mut length, &mut data).is_null() } { return Err(Error::Type("Argument to TextDecoder.decode is not an ArrayBufferView".to_owned())); } let buffer = unsafe { ...
random_line_split
textdecoder.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::TextDecoderBinding; use dom::bindings::codegen::Bindings::TextDecoderBinding...
(global: GlobalRef, encoding: EncodingRef, fatal: bool) -> Root<TextDecoder> { reflect_dom_object(box TextDecoder::new_inherited(encoding, fatal), global, TextDecoderBinding::Wrap) } /// https://encoding.spec.whatwg.org/#dom-textdecoder pub fn C...
new
identifier_name
textdecoder.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::TextDecoderBinding; use dom::bindings::codegen::Bindings::TextDecoderBinding...
/// https://encoding.spec.whatwg.org/#dom-textdecoder pub fn Constructor(global: GlobalRef, label: DOMString, options: &TextDecoderBinding::TextDecoderOptions) -> Fallible<Root<TextDecoder>> { let encoding = match encoding_from_...
{ reflect_dom_object(box TextDecoder::new_inherited(encoding, fatal), global, TextDecoderBinding::Wrap) }
identifier_body
hunter.rs
// // Copyright 2021 The Project Oak Authors // // 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 o...
// use common::module_common::{move_by, print_str, srand, Context, GRID_H, GRID_W}; use common::println; use common::shared::{cptr, State}; #[no_mangle] pub extern "C" fn malloc_(size: usize) -> cptr { let vec: Vec<u8> = Vec::with_capacity(size); let ptr = vec.as_ptr(); std::mem::forget(vec); // Leak the ...
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License.
random_line_split